我想扩展Array.prototype以包含一个正方形函数。我有这样的:扩展Array.prototype返回undefined
Array.prototype.square = function(){
return this.forEach(function(el){
return (el * el)
});
}
当我打电话阵列上这个功能,说arr = [2, 2, 2]
则返回undefined。如果我在那里添加一个console.log,我可以看到forEach函数的回调函数正确执行 - 它记录了三次。为什么这个函数返回undefined而不是[4,4,4]的新数组?
'.forEach()'函数不返回值。 – Pointy
注意:如果可用,使用Object.defineProperty(Array.prototype,'square',{value:function(){...}})'来防止函数成为_every_数组实例的枚举属性。 – Alnitak