ES6
新增 Array.from()
方法,从一个类数组或可迭代对象中创建一个新的数组实例
语法
Array.from(arrayLike[, mapFn[, thisArg]])
参数
arrayLike
想要转换成数组的伪数组对象或可迭代对象
- 这里的伪数组对象需要有一个
length
属性,length
决定了新数组的长度,数组对应位置元素如果缺失,以undefined
补全,如果length
属性缺失会使得新数组的长度为0
let arrayLike = {
0: 'Tom',
1: 23,
2: [1, 2, 3],
length: 5
}
Array.from(arrayLike) // ["Tom", 23, Array(3), undefined, undefined]
let arrayLike = {
0: 'Tom',
1: 23,
2: [1, 2, 3]
}
Array.from(arrayLike) // []
- 伪数组对象的
key-value
中key
必须为数字索引或者数字索引的字符串形式,否则这个属性将被忽略,索引对应的value
就是新数组该索引的值,如果有多个索引相同,则后面的覆盖前面的
let arrayLike = {
'0': 'Tom',
'e': 23,
2: [1, 2, 3],
0: 'Jack',
length: 4
}
Array.from(arrayLike) // ["Jack", undefined, Array(3), undefined]
- 可迭代对象必须实现了 @@iterator 方法,例如
String Map Set Array
等
Array.from('this is a string') // ["t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "s", "t", "r", "i", "n", "g"]
Array.from(new Map().set(true, 7)) // [true, 7]
Array.from(new Set([1, '2', 'r', 'r', 5])) // [1, "2", "r", 5] 这个方法通常可以用来进行快速数组去重
Array.from(new Array([1, '2', 'r', 'r', 5])) // [1, "2", "r", "r", 5]
mapFn(可选参数)
新数组中每个元素都会执行该回调函数,Array.from(obj, mapFn, thisArg)
效果等同于Array.from(obj).map(mapFn, thisArg)
thisArg(可选参数)
执行回调函数mapFn
时的this
对象
返回值
新的数组实例