Array.from()的第一个参数是一个类数组对象,即任何可迭代的结构,或者一个有length属性和可索引属性的结构
1,字符串会被拆分为单字符数组
console.log(Array.from('matt'));
//['m','a','t','t']
2,可以使用from将集合和映射转换为一个新数组
const m = new Map().set(1,2).set(3,4);
const s = new Set().add(1).add(2).add(3).add(4);
console.log(Array.from(m));
//[[1,2],[3,4]]
console.log(Array.from(s));
//[1,2,3,4]
3,Array.from()对现有数组执行浅复制
const a1 = [1,2,3,4];
const a2 = Array.from(a1);
console.log(a1);//[1,2,3,4]
alert(a1 === a2);//false
4,可以使用任何可迭代对象
const iter = {
*Symbol.iterator](){
yield 1;
yield 2;
yield 3;
yield 4;
}
};
console.log(Array.from(iter));//[1,2,3,4]
5,arguments对象可以被轻松地转换为数组
function getArgsArray(){
return Array.from(arguments);
}
console.log(getArgsArray(1,2,3,4));//[1,2,3,4]
6,from()也能转换带有必要属性的自定义对象
const arryaLikeObject ={
0:1,
1:2,
2:3,
3:4,
length:4
};
console.log(Array.from(arrayLikeObject));
//[1,2,3,4]
7,from方法可以接收第二个可选得映射函数参数,还可以接收第3个参数,用于指定映射函数中this的值
const a1 = [1,2,3,4];
const a2 = Array.from(a1,x =>x**2);
const a3 = Array.from(a1,function(x){return x**this.exponent},{exponent:2});
console.log(a2);
//[1,4,9,16]
console.log(a3);
//[1,4,9,16]