admin管理员组

文章数量:1429064

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]?

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]?

Share Improve this question asked Feb 12, 2014 at 16:20 Chris CloutenChris Clouten 1,0853 gold badges12 silver badges24 bronze badges 2
  • 1 The .forEach() function does not return a value. – Pointy Commented Feb 12, 2014 at 16:22
  • NB: if available, use Object.defineProperty(Array.prototype, 'square', { value: function() { ... } }) to prevent your function being an enumerable property of every array instance. – Alnitak Commented Feb 12, 2014 at 16:25
Add a ment  | 

2 Answers 2

Reset to default 7

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 p.s.w.g. said, .map is the appropriate function, but in a ment 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.

本文标签: javascriptExtending Arrayprototype returning undefinedStack Overflow