简体   繁体   English

扩展Array.prototype返回未定义

[英]Extending Array.prototype returning undefined

I'm trying to extend Array.prototype to include a square function. 我正在尝试扩展Array.prototype以包括平方函数。 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. 当我在数组上调用此函数时,说arr = [2, 2, 2]它将返回未定义的值。 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. 如果在其中添加console.log,我可以看到forEach函数的回调函数正确执行-它记录4次三遍。 Why is this function returning undefined instead of a new array of [4, 4, 4]? 为什么此函数返回undefined而不是返回[4,4,4]的新数组?

The forEach method does not return a value. forEach方法不返回值。 You need to use map : 您需要使用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 . 正如pswg所说, .map是合适的功能,但是在注释中,您询问了有关使用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. .map()更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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