手撕代码之 Array.from()

369 阅读1分钟

使用方法

Array.from() 方法从一个类似数组可迭代对象创建一个新的浅拷贝的数组实例。

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

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

let a = { 0: 'demo', 1: 'demo2', length: 2 };
let b = Array.from(a);
console.log(b) //=>['demo', 'demo2']

语法:Array.from(arrayLike[, mapFn[, thisArg]])

  • arrayLike:想要转换成数组的伪数组对象或可迭代对象。
  • mapFn(可选):如果指定了该参数,新数组中的每个元素会执行该回调函数。
  • thisArg(可选):可选参数,执行回调函数 mapFn 时 this 对象。

模拟实现

Array.myFrom = (data, mapFun = (item) => item) => {
  let res = [];
  
  if (data.length) {
    // 有 length 属性的对象
    for (let i = 0; i < data.length; i++) {
      res[i] = mapFun(data[i]) || null;
    }
  } else if (typeof data[Symbol.iterator] === 'function') { 
    // 可迭代对象
    data.forEach((item) => {
      res.push(mapFun(item));
    })
  }
  return res;
}