简体   繁体   中英

Extending Array.prototype returning undefined

I'm trying to extend Array.prototype to include a square function. I have this:

Array.prototype.square = function(){
  return this.forEach(function(el){
    return (el * el)
  });
}

When I call this function on an array, say arr = [2, 2, 2] it returns undefined. If I add a console.log in there I can see that the callback function for the forEach function executes properly -- it logs 4 three times. Why is this function returning undefined instead of a new array of [4, 4, 4]?

The forEach method does not return a value. You need to use map :

Array.prototype.square = function(){
  return this.map(function(el){
    return (el * el)
  });
}

console.log([2, 2, 2].square()); // [4, 4, 4]

As pswg said, .map is the appropriate function, but in a comment you asked about using forEach . To get this to work, you'd have to create a temporary array:

Array.prototype.square = function(){
  var tmp = [];

  this.forEach(function(el){
    tmp.push(el * el)
  });

  return tmp;
}

console.log([2, 2, 2].square()); // [4, 4, 4]

.map() is better, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM