ES6-Array.from()方法
一、介绍
Array.from()方法从一个类似数组或可迭代对象中创建一个新的数组实例。
const bar = ["a", "b", "c"];
Array.from(bar);
// ["a", "b", "c"]
Array.from('foo');
// ["f", "o", "o"]
语法
Array.from(arrayLike[, mapFunction[, thisArg]])
- arrayLike:必传参数,想要转换成数组的伪数组对象或可迭代对象。
- mapFunction:可选参数,mapFunction(item,index){...} 是在集合中的每个项目上调用的函数。返回的值将插入到新集合中。
- thisArg:可选参数,执行回调函数 mapFunction 时 this 对象。这个参数很少使用。
- 返回一个新的数组实例
描述
- 伪数组对象:拥有一个
length属性和若感觉索引属性的任意对象 - 可迭代对象:可以获取对象中的元素,如
Map和Set等
二、用法
1. 从伪数组对象中获取数组
let arrayLike = {
0: 'tom',
1: '65',
2: '男',
3: ['jane','john','Mary'],
'length': 4
}
let arr = Array.from(arrayLike)
console.log(arr) // ['tom','65','男',['jane','john','Mary']]
如果去掉length属性,输出的arr为空数组[]
let arrayLike = {
'name': 'tom',
'age': '65',
'sex': '男',
'friends': ['jane','john','Mary'],
length: 4
}
let arr = Array.from(arrayLike)
console.log(arr) // [ undefined, undefined, undefined, undefined ]
改一下代码,前面的索引属性换成字符串的话,会输出四个undefined的数组
2. 从字符串中获取数组
console.log(Array.from('zoro')); //["z", "o", "r", "o"]
2. 从Set中获取数组
let arr = [1,2,3]
let set = new Set(arr)
console.log(Array.from(set)) // [1, 2, 3]
还可以加第二个参数,类似于数组的map方法,对里面的每个元素进行处理
let arr = [1,2,3]
let set = new Set(arr)
console.log(Array.from(set, item => item + 1)) // [2, 3, 4]
2. 从Map中获取数组
var m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m); // [[1, 2], [2, 4], [4, 8]]
另一种方法,用扩展运算符转为数组
const myMap = new Map().set(true, 7)
console.log(myMap); //Map(1) {true => 7}
console.log([...myMap]); //[true ,7]

浙公网安备 33010602011771号