accessing arguments in callback array.protoype

后端 未结 2 1809
无人及你
无人及你 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:33

    You just need to add another argument to your callback function which is your index.

    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);
      return item * 2;
    })
    console.log(x);

提交回复
热议问题