Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

javascript - Node JS / V8 destructuring bug?

Using node 8.4.0:

$ node
> {x, y} = {x: 1, y: 2}
{ x: 1, y: 2 }
>

However, the following errors also non interactive: (the only diff is the semicolon)

$ node
> {x, y} = {x: 1, y: 2};
...

Also in Chrome console:

> {x,y} = {x:1, y:2}
< {x: 1, y: 2}
> {x,y} = {x:1, y:2};
x VM253:1 Uncaught SyntaxError: Unexpected token =

Can anyone explain this?

Clarification

This is not about let, var or cosnt destructuring which works as intended. This is about previously defined variables, (or non strict mode): from chrome console:

> 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 =
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The proper syntax to destructure an object to existing variables is

({x, y} = {x: 1, y: 2});

This allows {x, y} = {x: 1, y: 2} to be an expression. Otherwise {x, y} is interpreted as a block with comma operator, this results in Unexpected token = error.

It works without parentheses and a semicolon in console because it is treated as an expression there. This is efficiently same thing as

console.log({x, y} = {x: 1, y: 2});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...