Array.from()把一个类数组或者可迭代对象转换为数组,也可用于浅拷贝数组
什么是类数组??
- 具有length属性,并且有索引 , 如:通过querySelectorAll选择的dom元素集合,字符串
let obj = {
0: 'a',
1: 'b',
length: 2
}
let str = 'abc'
let m = new Map().set(1, 2, 3)
let s = new Set().add(1).add(2).add(3)
console.log( Array.from(obj)) //[a,b]
console.log( Array.from(str)) // [a,b,c]
console.log( Array.from(m)) // [[1,2]]
console.log( Array.from(s)) //[1,2,3]
Array.from() 有两个可选参数mapFn,thisArg
mapFn: 类似map函数,对传入的每一项进行操作
let str = 'abc'
console.log(Array.from(str,function(item,index) {
return item+index
}))
// [a0,b1,c2]
thisArg: 将参数赋值给this,从而使mapFn可以通过this调用
let str = 'abc'
let arr = Array.from(str,function(item,index) {
return item+index*this.x
},{x:10})
console.log(arr) // [a0,b10,c20]