[英]Why does adding parentheses prevent an error?
Why is it when I write {}.key = 0
in the chrome console I get an error:为什么当我在 Chrome 控制台中写入
{}.key = 0
时出现错误:
> {}.key = 0
> Uncaught SyntaxError: Unexpected token .
But when I encapsulate the above expression in parentheses ( ( )
) I get no error:但是当我将上面的表达式封装在括号 (
( )
) 中时,我没有得到任何错误:
> ({}.key = 0)
> 0
What exactly is going on here?这里到底发生了什么? I would have thought the same error I got in the first scenario still applied to the second?
我会认为我在第一个场景中遇到的错误仍然适用于第二个场景?
Image of console output :控制台输出图像:
{ }
are overloaded in JavaScript syntax. { }
在 JavaScript 语法中被重载。 They're used for both blocks (of statements) and object literals.它们用于块(语句)和对象文字。 The rule is: If a
{
appears at the start of a statement, it is parsed as a block;规则是:如果一个
{
出现在语句的开头,它被解析为一个块; otherwise it is an object literal.否则它是一个对象字面量。
In {}.key
the {
appears at the start of the statement.在
{}.key
, {
出现在语句的开头。 It parses as它解析为
{
// this is an empty block
}
.key // syntax error here
Adding any token before {
(such as (
) makes it parse as an object literal. For example, 42, {}.key = 0
would also work.在
{
之前添加任何标记(例如(
) 使其解析为对象字面量。例如, 42, {}.key = 0
也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.