[英]How is this reduce operation mutating my original array?
I want to reduce the items
array so that it includes a single element for "apple" with an updated quantity.我想减少
items
数组,以便它包含“apple”的单个元素和更新的数量。 The code below returns the correct reduced array, but it also mutating the original items
array and I don't understand why.下面的代码返回正确的缩减数组,但它也改变了原始
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} // ]
You are adding objects from items
into newArray
when you call newArray.push(currentItem)
.当您调用
newArray.push(currentItem)
时,您正在将items
中的对象添加到newArray
中。 newArray
will hold the same objects (with the same reference) as in items
. newArray
将保存与items
中相同的对象(具有相同的引用)。 When you later call newArray[indexForCurrentItem].qty += currentItem.qty
you update the object that is present in both arrays.当您稍后调用
newArray[indexForCurrentItem].qty += currentItem.qty
时,您会更新 arrays 中存在的 object。
A simple fix would be to add copies of objects to the new array.一个简单的解决方法是将对象的副本添加到新数组中。
newArray.push(Object.assign({}, currentItem))
With this change newArray
will hold (shallow) copies of objects.通过此更改
newArray
将保存对象的(浅)副本。 If you change the copy the original in items
will be unaffected.如果您更改副本,
items
中的原件将不受影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.