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

Object deconstruction assignment without variable declaration in ES6

是否可以在 ES6 中使用解构赋值表达式而不需要声明变量?

换句话说,为什么下面的代码语法不正确?

(我知道有很多方法可以重写这段代码。)

'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);

中括号解释为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, i.e. no redeclaration, but invalid expression
}
console.log(var1);
console.log(var2);

您可以组合它们,并使用 short-circuit evaluation to use a fallback (|| {}), and then use defaults 作为值,而不是声明变量和条件解构:

'use strict';

const obj = { group: { var1: 'newVal1', var2: 'newVal2' } };

const { group: { var1 = 'defaultVal1', var2 = 'defaultVal2' } = {}} = obj || {};

console.log(var1);
console.log(var2);