对象解构没有var [英] object destructuring without var

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

问题描述

如果前面没有 var 关键字,为什么对象解构会引发错误?

Why does object destructuring throw an error if there is no var keyword in front of it?

{a, b} = {a: 1, b: 2};

throws SyntaxError:expected expression,got'='

以下三个示例工作没有问题

The following three examples work without problems

var {a, b} = {a: 1, b: 2};
var [c, d] = [1, 2];
    [e, f] = [1, 2];

奖金问题:为什么我们不需要 var 用于数组解构?

Bonus question: Why do we not need a var for array destructuring?

我遇到了这样的问题,像

I ran into the problem doing something like

function () {
  var {a, b} = objectReturningFunction();

  // Now a and b are local variables in the function, right?
  // So why can't I assign values to them?

  {a, b} = objectReturningFunction();
}


推荐答案

code> {...} JavaScript中具有多重含义的运算符。

The issue stems from the {...} operators having multiple meanings in JavaScript.

{出现在语句的开头,它始终代表一个,不能分配给。如果在语句中作为表达式出现,那么它将代表一个对象。

When { appears at the start of a Statement, it'll always represent a block, which can't be assigned to. If it appears later in the Statement as an Expression, then it'll represent an Object.

var 有助于区分这个区别,因为语句不能遵循分组括号

The var helps make this distinction, since it can't be followed by a Statement, as will grouping parenthesis:

( {a, b} = objectReturningFunction() );

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

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