accessing arguments in callback array.protoype

后端 未结 2 1812
无人及你
无人及你 2020-12-22 06:53

I am implementing the map function. To access the array I am mapping over I am using this based on a question I had earlier. Now I am wondering how to access di

2条回答
  •  再見小時候
    2020-12-22 07:43

    You need to hand over the index as second parameter for the callback

    Array.prototype.mapz = function(callback) {
      const arr = [];
      for (let i = 0; i < this.length; i++) {
        arr.push(callback(this[i], i));
      }
      return arr;
    };
    
    let x = [1, 12, 3].mapz((item, index) => {
      console.log(index, item);
      return item * 2;
    })
    console.log(x);

提交回复
热议问题