没有 var、let 或 const 的对象解构 [英] Object destructuring without var, let or const
问题描述
为什么对象解构前没有var
关键字会报错?
Why does object destructuring throw an error if there is no var
keyword in front of it?
{a, b} = {a: 1, b: 2};
抛出 SyntaxError:预期的表达式,得到 '='
以下三个例子都没有问题
The following three examples work without problems
var {a, b} = {a: 1, b: 2};
var [c, d] = [1, 2];
[e, f] = [1, 2];
额外问题:为什么我们不需要 var
进行数组解构?
Bonus question: Why do we not need a var
for array destructuring?
我在做类似的事情时遇到了问题
I ran into the problem doing something like
function () {
var {a, b} = objectReturningFunction();
// Now a and b are local variables in the function, right?
// So why can't I assign values to them?
{a, b} = objectReturningFunction();
}
推荐答案
问题源于 {...}
运算符在 JavaScript 中具有多重含义.
The issue stems from the {...}
operators having multiple meanings in JavaScript.
当 {
出现在 Statement 的开头时,它总是代表一个 block,无法分配到.如果它稍后出现在 Statement 中作为 Expression,那么它将代表一个对象.
When {
appears at the start of a Statement, it'll always represent a block, which can't be assigned to. If it appears later in the Statement as an Expression, then it'll represent an Object.
var
有助于区分这一点,因为它后面不能跟 Statement,分组括号:
The var
helps make this distinction, since it can't be followed by a Statement, as will grouping parenthesis:
( {a, b} = objectReturningFunction() );
注意:在没有声明的情况下使用对象字面量解构赋值时,赋值语句周围的括号 ( ... ) 是必需的.
Notes: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.
{a, b} = {a: 1, b: 2} 不是有效的独立语法,因为左侧的 {a, b} 被视为块而不是对象文字.
{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.
然而,({a, b} = {a: 1, b: 2}) 是有效的,var {a, b} = {a: 1, b: 2} 也是如此
However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}
你的 ( ... ) 表达式前面需要有一个分号,否则它可以用来执行上一行的函数.
Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.
这篇关于没有 var、let 或 const 的对象解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!