Method of use

The array.from () method creates a new shallow copy of an Array instance from an array-like or iterable.

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']
Copy the code

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

  • arrayLike: A pseudo-array object or iterable that you want to convert to an array.
  • mapFn(Optional) : If specified, each element in the new array executes the callback function.
  • thisArg(Optional) : This object is optional when the callback function mapFn is executed.

Analog implementation

Array.myFrom = (data, mapFun = (item) => item) = > {
  let res = [];
  
  if (data.length) {
    // Object with length attribute
    for (let i = 0; i < data.length; i++) {
      res[i] = mapFun(data[i]) || null; }}else if (typeof data[Symbol.iterator] === 'function') { 
    // Iterable
    data.forEach((item) = >{ res.push(mapFun(item)); })}return res;
}
Copy the code