Javascript 这个reduce操作是如何改变我原来的数组的?
我想减少Javascript 这个reduce操作是如何改变我原来的数组的?,javascript,arrays,Javascript,Arrays,我想减少items数组,使其包含一个更新数量的“apple”元素。下面的代码返回了正确的简化数组,但它也改变了原始的项数组,我不明白为什么 const项=[ {名称:“苹果”,数量:1}, {名称:“香蕉”,数量:1}, {名称:“苹果”,数量:3} ]; const reducedItems=items.reduce(函数(newArray,currentItem){ const indexForCurrentItem=newArray.findIndex( ({name})=>name==
items
数组,使其包含一个更新数量的“apple”元素。下面的代码返回了正确的简化数组,但它也改变了原始的项
数组,我不明白为什么
const项=[
{名称:“苹果”,数量:1},
{名称:“香蕉”,数量:1},
{名称:“苹果”,数量:3}
];
const reducedItems=items.reduce(函数(newArray,currentItem){
const indexForCurrentItem=newArray.findIndex(
({name})=>name==currentItem.name
);
//如果当前项不在newArray中,请添加它
//但如果它已经在newArray中,则在那里更新其quantity属性
indexForCurrentItem==-1
?新建数组。推送(当前项)
:newArray[indexForCurrentItem].qty+=currentItem.qty;
返回新数组;
}, []);
console.log(reducedItems);
控制台日志(项目);
//reducedItems是正确的:[{name:“apples”,数量:4},{name:“bananas”,数量:1}]
//但现在的项目是:
// [
//{名称:“苹果”,数量:4},
//{名称:“香蕉”,数量:1},
//{名称:“苹果”,数量:1}
//]
调用newArray.push(currentItem)
时,您正在将对象从items
添加到newArray
中newArray
将保存与items
中相同的对象(具有相同的引用)。稍后调用newArray[indexforcurrentem].qy+=currentItem.qy
时,将更新两个数组中存在的对象
一个简单的修复方法是将对象的副本添加到新数组中
newArray.push(Object.assign({}, currentItem))
通过此更改,
newArray
将保存对象的(浅层)副本。如果更改副本,items
中的原始项将不受影响。调用newArray.push(currentItem)
时,您正在将对象从items
添加到newArray
newArray
将保存与items
中相同的对象(具有相同的引用)。稍后调用newArray[indexforcurrentem].qy+=currentItem.qy
时,将更新两个数组中存在的对象
一个简单的修复方法是将对象的副本添加到新数组中
newArray.push(Object.assign({}, currentItem))
通过此更改,
newArray
将保存对象的(浅层)副本。如果更改副本,则items
中的原始副本将不受影响。一种解决方案是在将对象推入数组函数(newArray,{…currentItem})
之前对其进行浅层复制。一种解决方案是在将对象推入数组函数(newArray,{…currentItem})
。