簡體   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