es6-Array.from

290 阅读1分钟

Array.from(arr, mapfn,thisArg)方法,用于将两类可以把对象转换为真正的数组:类似数组的对象和可遍历的对象(部署了Iterator接口的,String,ES6新增的Map和Set)。

  • 可以传3个参数,其中第一个是数组,必传
  • 第二个是一个函数(类似map函数),对数组元素进行操作后再返回数组,可选;
  • 第三个是对于this关键字的指向,可选。

类似数组的对象 : 必须有length属性 ,如果没有,转出的是空数组。所以任何有length属性的对象,都能通过这个方法转换为数组(此时扩展运算符...无法转换),length属性会决定转化的数组什么样子

let arrayLike = {
    '0': 'a', 
    '1': 'b',
    '2': 'c'
}
let arr = Array.from(arrayLike)
console.log(arr) 
运算结果为:
[]

let arrayLike1 = {
    '0': 'a', 
    '1': 'b',
    '2': 'c',length:2
}
let arr1 = Array.from(arrayLike1)
console.log(arr1) 
运算结果为:["a", "b"]

let arrayLike2 = {
    '0': 'a', 
    '1': 'b',
    '2': 'c',length:3
}
let arr2 = Array.from(arrayLike2)
console.log(arr2) 
运算结果为:["a", "b", "c"]


let arrayLike3 = {
    '0': 'a', 
    '1': 'b',
    '2': 'c',length:4
}
let arr3 = Array.from(arrayLike3)
console.log(arr3) 
运算结果为:["a", "b", "c", undefined]

复制数组:类似...扩展运算符的作用,如果传的是一个数组,那么返回相同数据的数组。

let arr4 = Array.from(arr2)
undefined
arr4
运算结果为:["a", "b", "c"]
arr4[0]=0
0
arr4
运算结果为:[0, "b", "c"]
arr2
运算结果为:["a", "b", "c"]

Array.from(arr,function) 可以接收,第二个参数,类似map方法的作用,对数组的每个元素处理后再返回新数组

let arr5 = Array.from(arr2, item => item + item)
undefined
arr5
原酸结果为:["aa", "bb", "cc"]
相当于:
Array.from(arr2).map(x=>x+x)
运算结果为:["aa", "bb", "cc"]