javascript - Extending Array.prototype returning undefined - Stack Overflow

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745542837a4632206.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信