当前位置:网站首页>Realize a simple version of array by yourself from

Realize a simple version of array by yourself from

2022-07-07 12:30:00 Xiaoding Chong duck!

purpose :

Array.from Method from an array like or iteratable object to create a new , Array instance of shallow copy .     ——MDN

See Array.from()

Use the syntax :

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

Code :

function myArrayFrom() {
   let arrayLike = arguments[0];
   //  Judge whether the first parameter is empty 
   if (arrayLike == null) {
      throw new TypeError("Array.from requires an array-like object - not null or undefined");
   }
   let fn = arguments.lenght > 1 ? arguments[1] : undefined;
   //  Judge whether the second parameter is a function 
   if (fn && !(typeof fn === 'function')) {
      throw new TypeError('Array.from: when provided, the second argument must be a function');
   }
   let thisArg =  arguments.lenght > 2 ? arguments[2] : undefined;
   let len = arrayLike.length;
   let i = 0, value;
   let arr = new Array(len);
   while (i < len) {
      value = arrayLike[i];
      if (fn) {
         arr[i] = !thisArg ? fn(value, i) : fn.call(thisArg, value, i);
      } else {
         arr[i] = value;
      }
      i++;
   }
   return arr;
}

verification :

function mySum () {
   console.log(arguments);
   console.log(myArrayFrom(arguments));
}

mySum(1,2,3,4,42,4,24);
/*
[Arguments] {
  '0': 1,
  '1': 2,
  '2': 3,
  '3': 4,
  '4': 42,
  '5': 4,
  '6': 24
}
*/
/*
[
   1, 2,  3, 4,
  42, 4, 24
]
*/

 

原网站

版权声明
本文为[Xiaoding Chong duck!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130617454431.html