1. 程式人生 > 其它 >js實現陣列map的方法

js實現陣列map的方法

技術標籤:jsmap實現js map

參考:https://www.cnblogs.com/suihang/p/10535002.html

 Array.prototype.newMap = function(fn) {
    var newArr = [];
    for(var i = 0; i<this.length; i++){
      newArr.push(fn(this[i],i,this))
    }
    return newArr;
 }
 var arr = [3, 4, 5];
 var newArr = arr.newMap(function(item, index,
arr) {   console.log(item, index, arr);  });  console.log(newArr); //3 0 [3, 4, 5] //4 1 [3, 4, 5] //10 5 [3, 4, 5] //[undefined, undefined, undefined]