定义与使用
Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
- 把伪数组转为数组,并返回新数组。
- 把可迭代对象(Map,Set),转为数组。
- 转为数组后,可选择性执行一个回调,作用到这个数组上。
输入
- arrayLike 想要转换成数组的伪数组对象(如arguments)或可迭代对象(Map,Set)。
- mapFn 可选 如果指定了该参数,新数组中的每个元素会执行该回调函数。
- thisArg 可选 可选参数,执行回调函数 mapFn 时 this 对象。
输出
一个新的数组实例。不会改变输入数据。
描述
Array.from() 可以通过以下方式来创建数组对象:
- 伪数组对象(拥有一个 length 属性和若干索引属性的任意对象)
- 可迭代对象(可以获取对象中的元素,如 Map和 Set 等)
- Array.from() 方法有一个可选参数 mapFn,让你可以在最后生成的数组上再执行一次 map 方法后再返回。也就是说 Array.from(obj, mapFn, thisArg) 就相当于 Array.from(obj).map(mapFn, thisArg),
应用
字符串转数组
Array.from('abc');
// ["a", "b", "c"]
Set 转数组并操作其元素
var mySet = new Set([1,2,3,4,5]);
Array.from(mySet,(item,index)=>{return index+item*2});
// [2, 5, 8, 11, 14]
Map转数组并操作
var myMap= new Map([[1, 2], [3, 4]]);
var arr = Array.from(myMap,(item,index)=>{return item*2});//[0, 2]
//转数组
var arr = Array.from(myMap);//[[1, 2], [3, 4]]
console.log(myMap);
// Map {1 => 2, 3 => 4}
对数组进行填充
// 用元素填充
Array.from('abc',(item,index)=>{return item});
// ["a", "b", "c"]
// 用索引填充
Array.from(Array(5),(item,index)=>{return index});
// [0, 1, 2, 3, 4]
总结
- 输出一个新的数组实例。不会改变输入数据。
- 可转伪数组,可迭代对象(Map,Set),将其转为数组
- Map转后是一个二维数组。
- 可用于配合Array(1000),快速通过索引填充一个数组。