【发布时间】: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