ES6 的新解构赋值特性现在已经相当有名了(live copy 在 Babel 的 REPL 上);对于已经存在的变量:
let a, b; // Existing variables
let o = {a: "a", b: "b"}; // An object to get values from
// ...
({a, b} = o); // Set them to the props from `o`
console.log(a); // "a"
console.log(b); // "b"
在 ES6 中有简单对话吗?根据同名变量在现有 对象上设置属性? (除了明显的 o.a = a; o.b = b;
)
请注意,我不是在谈论什么时候创建一个对象,我们可以使用美妙的新对象初始化语法来做到这一点,它让我们不会不必要地重复名称:
let a = "a";
let b = "b";
let o = {a, b};
但是如果我已经有一个对象,我可以在 ES6 中做一些结构化赋值吗?
最佳答案
我想到的最接近的方法是使用 Object.assign
和一个临时对象 ( live copy ):
let a = "a", b = "b"; // The variables
let obj = {c: "c"}; // The existing object
Object.assign(obj, {a, b}); // "Structuring" assignment, sort of
console.log(JSON.stringify(obj)); // "{"c":"c","a":"a","b":"b"}
它相当简单,但它是一个函数调用和一个临时对象。
更新: Bergi指出in a comment那there's a strawman proposal (link now dead) 用于 :=
运算符将执行此操作,并且他们的第一个用例确实是主要将我引向这个问题的用例:Constructors :
// From strawman proposal linked above, doesn't actually exist yet!
class Point {
constructor(x,y) {
this := {x,y} //define and initialize x and y properties of new object
// ^^
}
}
鉴于 strawman 存在,我怀疑现在 strawman 离线了,proposals repo 中没有关于assign
将是我在 ES6 中能做的最好的事情。:=
的信息.
关于javascript - ES6 结构分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30897961/