数组Array.from()用法
JavaScript数组的
Array.from()
方法用于将类似数组或可迭代对象(字符串、map、set)转换为真正的数组。
该方法的语法如下: Array.from(arrayLike[, mapFn[, thisArg]])
- arrayLike:想要转换成真实数组的类数组对象或可遍历对象。
- mapFn:可选参数,如果指定了该参数,则最后生成的数组会经过该函数的加工处理后再返回。
- thisArg:可选参数,执行
mapFn
函数时this
的值。
将类数组对象转换为真正的数组
(function(){
let arr = Array.from(arguments);
return arr; //[1, 2, 3]
})(1,2,3);
let arrayLike = {
0: 'book',
1: '50',
2: 'xx出版社',
3: '吧啦吧啦',
'length': 4
}
let arr = Array.from(arrayLike)
console.log(arr) // ['book','50','xx出版社','吧啦吧啦']
可迭代对象转换为数组
转换数组的同时可以使用mapFn处理每个元素
const myMap = new Map([
["a", 1],
["b", 2],
]);
const mySet = new Set(["A", "B", "C"]);
console.log(Array.from("hello")); // ['h', 'e', 'l', 'l', 'o']
console.log(Array.from("hello", (char) => char.toUpperCase())); // ['H', 'E', 'L', 'L', 'O']
console.log(Array.from(myMap)); // [['a',1],['b',2]]
console.log(Array.from(mySet)); // ["A", "B", "C"]
console.log(Array.from([1,2,3],x=>x+2)); // [ 3, 4, 5 ]
创建一个数字序列
console.log(Array.from({ length: 5 },(_,i) => i));//[ 0, 1, 2, 3, 4 ]
console.log(Array.from({ length: 5 },(_,i) => 1));//[ 1, 1, 1, 1, 1 ]
使用对象填充数组
const length = 3;
const objArr1 = Array.from({ length }, () => ({}));//[{}, {}, {}]
const objArr2 = Array(length).fill({});//[{}, {}, {}]
objArr1[0] === objArr1[1]; // => false
objArr2[0] === objArr2[1]; // => true
数组去重并合并
function combine() {
const arr = [].concat(...Array.from(arguments));
return Array.from(new Set(arr));
}
console.log(combine([1, 2, 3, 4], [1, 2, 4, 5])); // [1, 2, 3, 4, 5]
拷贝数组
//浅拷贝
const numbers = [1, 2, [1,2,3]];
const numbersCopy1 = Array.from(numbers);//[1, 2, [1,2,3]]
numbersCopy1[2][0] = 10;
console.log(numbers,numbersCopy1);//[ 1, 2, [ 10, 2, 3 ] ] [ 1, 2, [ 10, 2, 3 ] ]
//多维数组深拷贝,通过第二个参数mapFn对数组元素递归调用。
const numbers = [1, 2, [1,2,3]];
function recursiveClone(val) {
return Array.isArray(val) ? Array.from(val, recursiveClone) : val;
}
const numbersCopy2 = recursiveClone(numbers);
numbersCopy2[2][0] = 10;
console.log(numbers,numbersCopy2);//[ 1, 2, [ 1, 2, 3 ] ] [ 1, 2, [ 10, 2, 3 ] ]