在Javascript中,为什么{a:1} == {a:1}给出错误,({a:1})== {a:1}将会工作?

这是在Firebug中完成的:

>>> {a : 1} == {a : 1}
SyntaxError: syntax error
[Break On This Error] {a : 1} == {a : 1} 

>>> ({a : 1}) == {a : 1}
false

所以需要({a:1})== {a:1},为什么呢?

因为{a:1}是一个声明,它不允许跟随==

({a:1})是一个表达式,允许后跟==

这基本上是语法中定义的规则。

但是请注意({a:1} == {a:1})有效。所以等价表达式是有效的。

这意味着{a:1} == {a:1}根本不是一个有效的语句。

12.4 of the ES5.1 spec

NOTE An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

作为旁注,你会发现

({a:1})!= {a:1},因为它们是两个新对象

翻译自:https://stackoverflow.com/questions/7713669/in-javascript-why-does-a-1-a-1-give-an-error-and-a-1

转载注明原文:在Javascript中,为什么{a:1} == {a:1}给出错误,({a:1})== {a:1}将会工作?