Node JS / V8解构bug? [英] Node JS / V8 destructuring bug?

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

问题描述

使用节点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};
...

同样在Chrome控制台中:

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?

这与let,var或cosnt destructuring无关。这是关于先前定义的变量,(或非严格模式):来自chrome控制台:

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 =


推荐答案

将对象解构为现有变量的正确语法是

The proper syntax to destructure an object to existing variables is

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

这允许 {x,y} = {x:1,y: 2} 是一个表达式。否则 {x,y} 被解释为带逗号运算符的块,这会导致 Unexpected token = 错误。

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

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

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