gpt4 book ai didi

javascript - ES6 更改对象值简写

转载 作者:行者123 更新时间:2023-12-02 14:11:17 24 4
gpt4 key购买 nike

在我看来,曾经见过比这更短的解决方案:

let obj = { id: 12345, name: "Some name", desc: "Description" }

someFunction(id, name, desc) {
obj.id = id;
obj.name= name;
obj.desc= desc;
}

有人可以告诉我是否有更快的方法来分配具有相同名称的新值?

最佳答案

我认为您正在寻找 Object.assign() :

let obj = {id: 12345, name: 'Some name', desc: 'Description'}
Object.assign(obj, {id: 54321})
console.log(obj) // {id: 54321, name: 'Some name', desc: 'Description'}
Object.assign(obj, {id: 123, name: 'Some other name', desc: 'New description'})
console.log(obj) // {id: 123, name: 'Some other name', desc: 'New description'}

关于javascript - ES6 更改对象值简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39538783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com