ES6更改对象速记速记

时间:2016-09-16 19:22:43

标签: javascript ecmascript-6 shorthand

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

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

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

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

3 个答案:

答案 0 :(得分:2)

我认为您正在寻找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'}




答案 1 :(得分:0)

你指的是财产简写吗?

let id = '12345';
let name = 'Some name';
let desc = 'Description';

let obj = { id, name, desc };

答案 2 :(得分:0)

您可以使用Object.assign

function someFunction(id, name, desc) {
  Object.assign(obj, {id, name, desc});
}