美文网首页
Array.from

Array.from

作者: 卡卡的尼奇 | 来源:发表于2019-04-28 14:35 被阅读0次

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-valuekey必须为数字索引或者数字索引的字符串形式,否则这个属性将被忽略,索引对应的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对象

返回值

新的数组实例

相关文章

网友评论

      本文标题:Array.from

      本文链接:https://www.haomeiwen.com/subject/tfbdnqtx.html