Chr*_*ten 1 javascript arrays prototype
我正在尝试扩展Array.prototype以包含一个方形函数.我有这个:
Array.prototype.square = function(){
return this.forEach(function(el){
return (el * el)
});
}
Run Code Online (Sandbox Code Playgroud)
当我在一个数组上调用这个函数时,说它arr = [2, 2, 2]返回undefined.如果我在那里添加一个console.log,我可以看到forEach函数的回调函数正确执行 - 它记录4次三次.为什么这个函数返回undefined而不是[4,4,4]的新数组?
Array.prototype.square = function(){
return this.map(function(el){
return (el * el)
});
}
console.log([2, 2, 2].square()); // [4, 4, 4]
Run Code Online (Sandbox Code Playgroud)