Array.from

2019-04-28  本文已影响0人  卡卡的尼奇

ES6 新增 Array.from() 方法,从一个类数组或可迭代对象中创建一个新的数组实例

语法

Array.from(arrayLike[, mapFn[, thisArg]])

参数

arrayLike
想要转换成数组的伪数组对象或可迭代对象

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) // []
let arrayLike = {
  '0': 'Tom',
  'e': 23,
  2: [1, 2, 3],
  0: 'Jack',
  length: 4
}
Array.from(arrayLike) // ["Jack", undefined, Array(3), undefined]
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对象

返回值

新的数组实例

上一篇 下一篇

猜你喜欢

热点阅读