【问题标题】:Javascript Array.reduce weird behaviourJavascript Array.reduce 奇怪的行为
【发布时间】:2020-05-13 08:49:31
【问题描述】:

我有这个小代码sn-p:

let data = [1, 2];
let newBody = {};

let newArray = data.reduce((acc, current) => {
  newBody.doc = current;
  acc.push(newBody);
  return acc;
}, []);

结果是:

newArray = [ { doc: 2 }, { doc: 2 } ]

如果我在迭代中重新声明空的 newBody,它工作正常。 但是,如果我在获取最后一个数组元素的值并将其应用于所有其他元素之外声明它,我不知道为什么。

【问题讨论】:

  • 您一遍又一遍地使用 same 对象引用,修改 one 对象,并将对同一对象的多个引用推送到数组中. If I'm redeclaring the empty newBody inside the iteration, its working fine.
  • 另外,这是.map() 的工作,而不是.reduce()。您的代码的作用相当于:jsfiddle.net/khrismuc/82ezLu3o
  • @MarkMeyer 是的,正如其中一条评论所说,因为闭包,所以我想我必须更深入地研究闭包。 ChrisG - 这是我在 reduce 中所做工作的简化版本,这就是为什么我应该使用 .map

标签: javascript arrays


【解决方案1】:

您正在使用意外关闭。将newBody 放在适当的范围内:

let data = [1, 2];

let newArray = data.reduce((acc, current) => {
  let newBody = {};
  newBody.doc = current;
  acc.push(newBody);
  return acc;
}, []);

【讨论】:

    猜你喜欢
    • 2019-04-03
    • 1970-01-01
    • 2011-12-19
    • 2013-01-20
    • 1970-01-01
    • 2011-07-28
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多