javascript - ES6 结构分配?

标签 javascript variable-assignment ecmascript-6 destructuring

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 commentthere'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 存在,我怀疑现在 assign 将是我在 ES6 中能做的最好的事情。 strawman 离线了,proposals repo 中没有关于:= 的信息.

关于javascript - ES6 结构分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30897961/

相关文章:

javascript - Angular.js ng-repeat 使用 json 没有数据

javascript - Jquery: $.getJSON 不同的 url 端口

types - 如何在没有赋值的情况下注释 Rust 变量的数据类型?

c++ - if-check 和内联条件之间是否存在编译器差异?

javascript - 在 JavaScript ES6 中,for-in 循环和 for-of 循​​环中,变量 i 在 block 的每次迭代后不再存在?

javascript - 如何禁用 `datepickr.js` 中的过去日期?

javascript - 如何停止后台上传?

c# - 在结构中分配字段/属性

ecmascript-6 - 仅向 Node 添加 ES2015 模块支持

javascript - onClick 时 react 删除元素