Javascript对象解构 [英] Javascript object destructuring

查看:121
本文介绍了Javascript对象解构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在使用新的es6破解语法时无效?

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};

当这是:

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

所以这样:

var a = 1;
var b = 3;

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

我读过 MDN文档,我看到没有提到我正在尝试的语法,我认为必须有一个很好的理由,我只是想了解为什么。

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.

推荐答案

在你的例子中,第一个 {是不明确的,解析器将它解释为块的开头。虽然 {a,b,c} 是一个有效的块,但以下赋值运算符无效。

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});

示例

这与有一个对象字面本身(无论什么原因):

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

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

这篇关于Javascript对象解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆