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

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

问题描述

使用节点 8.4.0:

Using node 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 =

谁能解释一下?

这与按预期工作的 let、var 或 cosnt 解构无关.这是关于先前定义的变量,(或非严格模式):来自 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 解构错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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