【发布时间】:2021-12-30 01:54:20
【问题描述】:
我想更新shoppingItems 的对象值
使用 es6 扩展运算符 updateObj 更新对象但仅在函数内部
为什么shoppingItems 里面的Object没有改变它的值?
const kontorGoods = [{ cheese: 5.5 }, { rice: 2.5 }, { meat: 8.8 }];
const shoppingItems = [{ cheese: 5.5 }];
function updateValue(itemIndex){
const item = Object.values(kontorGoods[itemIndex])[0];
updateObj(shoppingItems, itemIndex);
console.log(updateObj(shoppingItems, itemIndex))
}
function updateObj(objArray, objIndex) {
const currentObjkey = Object.keys(objArray[objIndex])[0];
const currentObjValue = Object.values(objArray[objIndex])[0];
return {
...objArray[objIndex],
// add the key as a variable
[currentObjkey]: currentObjValue + currentObjValue,
};
}
updateValue(0)
console.log(shoppingItems)
【问题讨论】:
-
:-)...不是运算符。运算符不能做 rest 和 spread 语法所做的事情。
标签: javascript object mutation spread-syntax