accessing arguments in callback array.protoype

后端 未结 2 1804
无人及你
无人及你 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);

    0 讨论(0)
  • 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);

    0 讨论(0)
提交回复
热议问题