Skip to content

介绍下 Array.from()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Array.from() 是一个静态方法。

它可以将一个可迭代(iterable)对象或者像数组的对象(比如 {length: 4}转换为一个新的、浅克隆的数组。

js
// 像数组对象的意思是拥有 length 属性的对象

const arrayLikeObj = {
  length: 10
}

const arr = Array.from(arrayLikeObj, (_, key) => {
  // 0 1 2 3 4 5 6 7 8 9
  console.log(key)
  return key
})

console.log(arr.length) // 10

// [0,1,2,3,4,5,6,7,8,9]
console.log(arr)

// =====================================

console.log(Array.from('foo'));
// 输出:Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], (x) => x + x));
// 输出:Array [2, 4, 6]

Released under the MIT License.