Skip to content Skip to sidebar Skip to footer

Accessing Arguments In Callback Array.protoype

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 different arguments pa

Solution 1:

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);

Solution 2:

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);

Post a Comment for "Accessing Arguments In Callback Array.protoype"