【问题标题】:update Object value globally全局更新对象值
【发布时间】: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


【解决方案1】:

一个对象字面量创建一个new对象,它对你用来填充它的属性的东西没有任何影响,包括你使用扩展语法的任何对象。

要更新数组中的对象,写回数组:

    objArray[objIndex] = {
//  ^^^^^^^^^^^^^^^^^^^^^
      ...objArray[objIndex],
      // add the key as a variable
      [currentObjkey]: currentObjValue + currentObjValue,
    };

【讨论】:

    猜你喜欢
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    相关资源
    最近更新 更多