简体   繁体   English

对象解构和解构赋值之间的区别?

[英]Difference between object destructuring and and destructuring assignment?

For example if I have an object like this:例如,如果我有一个这样的对象:

let obj = { a: 1, b: 2 }
let { a, b } = obj;
console.log(a, b); // output 1, 2

But if a and b are initialized, like this:但是如果 a 和 b 被初始化,像这样:

let obj = { a: 1, b: 2 };
let a = 3, b = 4;
{ a, b } = obj;
console.log(a, b); // error

What is the difference between them, why the second output an error?它们有什么区别,为什么第二个输出错误?

You need parentheses around the destructuring assignment do distinguish destructuring from a block statement where an assignment to it is not possible.您需要在解构赋值周围加上括号,以便将解构与无法对其进行赋值的块语句区分开来。

Assignment without declaration : 无声明赋值

The round braces ( ... ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.在没有声明的情况下使用对象文字解构赋值时,赋值语句周围的圆括号( ... )是必需的语法。

{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}不是有效的独立语法,因为左侧的{a, b}被视为块而不是对象文字。

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}然而, ({a, b} = {a: 1, b: 2})是有效的, var {a, b} = {a: 1, b: 2}

NOTE: Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.注意:您的( ... )表达式需要以分号开头,否则它可用于执行前一行的函数。

 let obj = { a: 1, b: 2 }; let a = 3, b = 4; ({ a, b } = obj); console.log(a, b); // 1, 2

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

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