Javascript object destructuring

2020-02-13 02:48发布

问题:

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.

回答1:

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