繁体   English   中英

这个减少操作如何改变我的原始数组?

[英]How is this reduce operation mutating my original array?

我想减少items数组,以便它包含“apple”的单个元素和更新的数量。 下面的代码返回正确的缩减数组,但它也改变了原始items数组,我不明白为什么。

 const items = [ {name: "apples", qty: 1}, {name: "bananas", qty: 1}, {name: "apples", qty: 3} ]; const reducedItems = items.reduce(function(newArray, currentItem) { const indexForCurrentItem = newArray.findIndex( ({name}) => name === currentItem.name ); // if current item is not in newArray, add it // but if it is already in newArray, update its quantity property there indexForCurrentItem === -1? newArray.push(currentItem): newArray[indexForCurrentItem].qty += currentItem.qty; return newArray; }, []); console.log(reducedItems); console.log(items); // reducedItems is correct: [{name: "apples", qty: 4}, {name: "bananas", qty: 1}] // but items is now: // [ // {name: "apples", qty: 4}, // {name: "bananas", qty: 1}, // {name: "apples", qty: 1} // ]

当您调用newArray.push(currentItem)时,您正在将items中的对象添加到newArray中。 newArray将保存与items中相同的对象(具有相同的引用)。 当您稍后调用newArray[indexForCurrentItem].qty += currentItem.qty时,您会更新 arrays 中存在的 object。

一个简单的解决方法是将对象的副本添加到新数组中。

newArray.push(Object.assign({}, currentItem))

通过此更改newArray将保存对象的(浅)副本。 如果您更改副本, items中的原件将不受影响。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM