节点 JS / V8 解构错误?
Node JS / V8 destructuring bug?
使用节点 8.4.0:
$ node
> {x, y} = {x: 1, y: 2}
{ x: 1, y: 2 }
>
但是,以下错误也是非交互式的:(唯一的区别是分号)
$ node
> {x, y} = {x: 1, y: 2};
...
也在 Chrome 控制台中:
> {x,y} = {x:1, y:2}
< {x: 1, y: 2}
> {x,y} = {x:1, y:2};
x VM253:1 Uncaught SyntaxError: Unexpected token =
谁能解释一下?
澄清
这与按预期工作的 let、var 或 cosnt 解构无关。这是关于先前定义的变量,(或非严格模式):来自 chrome 控制台:
> let a, b;
< undefined
> [a, b] = [1, 2];
< >(2) [1, 2]
> a
< 1
> b
< 2
> {a, b} = {a:3, b:4}
< >{a: 3, b: 4}
> a
< 3
> b
< 4
> {a, b} = {a:3, b:4};
x VM1297:1 Uncaught SyntaxError: Unexpected token =
将对象解构为现有变量的正确语法是
({x, y} = {x: 1, y: 2});
这允许 {x, y} = {x: 1, y: 2}
成为一个表达式。否则 {x, y}
被解释为带有逗号运算符的块,这会导致 Unexpected token =
错误。
它在控制台中没有括号和分号就可以工作,因为它在那里被视为一个表达式。这实际上与
相同
console.log({x, y} = {x: 1, y: 2});
这不是错误,而是设计使然。参见“Assignment without declaration”:
A variable can be assigned its value with destructuring separate from its declaration.
var a, b;
({a, b} = {a: 1, b: 2});
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.
However, ({a, b} = {a: 1, b: 2})
is valid, as is var {a, b} = {a: 1, b: 2}
使用节点 8.4.0:
$ node
> {x, y} = {x: 1, y: 2}
{ x: 1, y: 2 }
>
但是,以下错误也是非交互式的:(唯一的区别是分号)
$ node
> {x, y} = {x: 1, y: 2};
...
也在 Chrome 控制台中:
> {x,y} = {x:1, y:2}
< {x: 1, y: 2}
> {x,y} = {x:1, y:2};
x VM253:1 Uncaught SyntaxError: Unexpected token =
谁能解释一下?
澄清
这与按预期工作的 let、var 或 cosnt 解构无关。这是关于先前定义的变量,(或非严格模式):来自 chrome 控制台:
> let a, b;
< undefined
> [a, b] = [1, 2];
< >(2) [1, 2]
> a
< 1
> b
< 2
> {a, b} = {a:3, b:4}
< >{a: 3, b: 4}
> a
< 3
> b
< 4
> {a, b} = {a:3, b:4};
x VM1297:1 Uncaught SyntaxError: Unexpected token =
将对象解构为现有变量的正确语法是
({x, y} = {x: 1, y: 2});
这允许 {x, y} = {x: 1, y: 2}
成为一个表达式。否则 {x, y}
被解释为带有逗号运算符的块,这会导致 Unexpected token =
错误。
它在控制台中没有括号和分号就可以工作,因为它在那里被视为一个表达式。这实际上与
相同console.log({x, y} = {x: 1, y: 2});
这不是错误,而是设计使然。参见“Assignment without declaration”:
A variable can be assigned its value with destructuring separate from its declaration.
var a, b; ({a, b} = {a: 1, b: 2});
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.However,
({a, b} = {a: 1, b: 2})
is valid, as isvar {a, b} = {a: 1, b: 2}