0


Array.prototype.myMap = function(callback) {
  const newArray = [];
  // Only change code below this line
  for(let i in this){
    newArray.push(callback(this[i], i, this))
  }
  // Only change code above this line
  return newArray;
};

console.log([1, 2, 3, 4, 5].myMap(item => item * 2))
type here

The result shows like

[ 2, 4, 6, 8, 10, NaN ]

I was expecting the result to be like this:

[ 2, 4, 6, 8, 10 ]

can anyone explain me why I have this null at the end of my arr if I use for in loop

**I know this works with normal for loop but I just wanna know why we get this problem **

  • 2
    Don't iterate arrays with `for ... in`, or even better, never use `for ... in` at all. Additionally, don't pollute natives, especially with enumerable properties, which is your downfall here. `for ... in` also iterates the prototype chain, and your prototype method is enumerable, so it will be included in the iteration. – ASDFGerte Jan 28 '23 at 16:39

1 Answers1

0

The for...in loop is finding the myMap property too. Either do a Object.hasOwn check, define the property with {enumerable: false}, or don't use for...in to loop.

Looping over the elements along with their indexes with Array#entries:

Array.prototype.myMap = function(callback) {
  const newArray = [];
  for(const [i, elem] of this.entries()){
    newArray.push(callback(elem, i, this))
  }
  return newArray;
};

console.log([1, 2, 3, 4, 5].myMap(item => item * 2))

Checking for own properties:

Array.prototype.myMap = function(callback) {
  const newArray = [];
  for(let i in this)
    if (Object.hasOwn(this, i))
      newArray.push(callback(this[i], i, this));
  return newArray;
};

console.log([1, 2, 3, 4, 5].myMap(item => item * 2))

Defining myMap with {enumerable: false}:

Object.defineProperty(Array.prototype, 'myMap', {
  value(callback) {
    const newArray = [];
    for (let i in this) {
      newArray.push(callback(this[i], i, this))
    }
    return newArray;
  },
  enumerable: false // this is the default, so it can be omitted
});
console.log([1, 2, 3, 4, 5].myMap(item => item * 2))
Unmitigated
  • 76,500
  • 11
  • 62
  • 80