简体   繁体   English

Object ES6 中没有变量声明的解构赋值

[英]Object deconstruction assignment without variable declaration in ES6

Is it possible to have a deconstructing assignment expression in ES6 without the need of declaring variables?是否可以在 ES6 中使用解构赋值表达式而不需要声明变量?

In other words, why is the following code syntactically incorrect?换句话说,为什么下面的代码在语法上不正确?

(I know there are a lot of ways this code could be rewritten.) (我知道有很多方法可以重写这段代码。)

'use strict';

let var1 = 'defaultVal1', var2 = 'defaultVal2';
const obj = { group: { var1: 'newVal1', var2: 'newVal2' } }
if (obj) {
  { group: { var1, var2 } } = obj; // No 'let'/'const' keyword, i.e. no redeclaration, but invalid expression
}
console.log(var1);
console.log(var2);

The brackets are interpreted as block statement , but you need an expression.括号被解释为块语句,但你需要一个表达式。 This can be archived by wrapping it with parentheses as an assignment without declaration .这可以通过用括号将其包装为没有声明的赋值来存档。

 'use strict'; let var1 = 'defaultVal1', var2 = 'defaultVal2'; const obj = { group: { var1: 'newVal1', var2: 'newVal2' } } if (obj) { ({ group: { var1, var2 } } = obj); // No 'let'/'const' keyword, ie no redeclaration, but invalid expression } console.log(var1); console.log(var2);

Instead of declaring the variables, and the conditionally destructure, you can combine them, and use short-circuit evaluation to use a fallback ( || {} ), and then use defaults as the values:您可以将它们组合起来,而不是声明变量和有条件的解构,并使用短路评估来使用回退( || {} ),然后使用默认值作为值:

 'use strict'; const obj = { group: { var1: 'newVal1', var2: 'newVal2' } }; const { group: { var1 = 'defaultVal1', var2 = 'defaultVal2' } = {}} = obj || {}; console.log(var1); console.log(var2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM