Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ecmascript 6 - Javascript object destructuring

Why is this not valid when using the new es6 destructuring syntax

var a, b, c;
{a, b, c } = {a:1, b:2, c:3};

when this is:

var {a, b, c } = {a:1, b:2, c:3};
console.log(a, ' ', b, ' ',c);

and so is this:

var a = 1;
var b = 3;

[a, b] = [b, a];

I had a read of the MDN documentataion and I see no mention of the syntax I'm attempting and I assume there must be a good reason, I'm just trying to understand why.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In your example, the first { is ambiguous and the parser will interpret it as the beginning of a block. While {a, b, c} is a valid block, the following assignment operator is not valid.

Wrap everything in parenthesis and it will parse correctly:

({a, b, c} = {a:1, b:2, c:3});

Example


This is similar to having an object literal by itself (for whatever reasons):

{"a": 42}   // parse error
({"a": 42}) // works

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...