为什么加括号可以防止错误? [英] Why does adding parentheses prevent an error?
问题描述
为什么在chrome控制台中编写 {}.key = 0
时会出现错误:
Why is it when I write {}.key = 0
in the chrome console I get an error:
> {}.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?
控制台输出图像:
推荐答案
{}
在JavaScript语法中已重载.它们用于(语句的)块和对象文字.规则是:如果在语句的开头出现 {
,则将其解析为块;否则,将其解析为块.否则它是对象文字.
{ }
are overloaded in JavaScript syntax. 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.
在 {}.key
中, {
出现在语句的开头.解析为
In {}.key
the {
appears at the start of the statement. It parses as
{
// this is an empty block
}
.key // syntax error here
在 {
之前添加任何令牌(例如(
))可以将其解析为对象文字,例如, 42,{} .key = 0
也可以.
Adding any token before {
(such as (
) makes it parse as an object literal. For example, 42, {}.key = 0
would also work.
这篇关于为什么加括号可以防止错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!