[英]Destructuring giving parsing error
I'm trying to understand destructuring in ES2015 (ECMAScript 6). 我试图了解ES2015(ECMAScript 6)中的解构。
I want a function to work on some variables and reassign the new variables back. 我希望函数对某些变量起作用并重新分配新的变量。
In the example below I have created a function to initialize foo and bar, and another function to change foo and bar. 在下面的示例中,我创建了一个函数来初始化foo和bar,以及另一个函数来更改foo和bar。
I have then created three functions that use foo and bar. 然后,我创建了三个使用foo和bar的函数。 Two of them work, and one does not.
其中两个工作,一个没有。 I can't seem to figure out why.
我似乎不知道为什么。
Please share any insight to assist my understanding. 请分享任何见解,以帮助我理解。
Thanks! 谢谢!
function initializeFooBar() { let foo = 1, bar = 2; return {foo, bar}; } function changeFooBar(f, b) { let foo = f*2, bar = b*2; return {foo, bar}; } function fooBarWorks() { let {foo, bar} = initializeFooBar(); console.log(foo + bar); // 3 } function fooBarAlsoWorks() { let f = 1, b = 2, {foo, bar} = changeFooBar(f, b); console.log(foo + bar); // 6 } function fooBarDoesntWork() { let {foo, bar} = initializeFooBar(); {foo, bar} = changeFooBar(foo, bar); // causes parsing error console.log(foo + bar); } fooBarWorks(); // writes 3 to console fooBarAlsoWorks(); // writes 6 to console fooBarDoesntWork(); // doesn't run due to "parsing error unexpected tolken ="
You need to change: 您需要更改:
{foo, bar} = changeFooBar(foo, bar);
to: 至:
({foo, bar} = changeFooBar(foo, bar));
because {
in this case is interpreted as a opening of a block of code. 因为
{
在这种情况下被解释为代码块的开头。
Surrounding the assignment with ()
disambiguates the meaning of {
. 用
()
包围赋值可消除{
的含义。
According to MDN documentation : 根据MDN文档 :
The
( .. )
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 isvar {a, b} = {a:1, b:2}
但是,
({a, b} = {a:1, b:2})
是有效的,var {a, b} = {a:1, b:2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.