扩展Array.prototype返回undefined

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]的新数组?

p.s*_*w.g 6

forEach方法不返回值.你需要使用map:

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)

  • @ChrisClouten`forEach`只是迭代而不返回任何东西 - "map"而是根据在原始元素的每个元素上调用回调的结果返回一个新数组. (3认同)