2014-02-12 61 views
1

我想扩展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]的新数组?

+1

'.forEach()'函数不返回值。 – Pointy

+0

注意:如果可用,使用Object.defineProperty(Array.prototype,'square',{value:function(){...}})'来防止函数成为_every_数组实例的枚举属性。 – Alnitak

回答

6

forEach方法不返回值。您需要使用map

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

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

为什么地图需要?为什么我无法使用forEach?我真的是一名JavaScript工程师,所以我一直在努力学习更多。请原谅我的无知! –

+1

s /真的/不真的/? – Alnitak

+3

@ChrisClouten'forEach'只是迭代而不返回任何东西 - 'map'会根据原始的每个元素上调用回调的结果返回一个新数组。 – Alnitak

2

由于p.s.w.g.说,.map是适当的功能,但在你问的关于使用forEach的评论。为了得到这个工作,你必须创建一个临时数组:

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()比较好,虽然。