In Javascript, why does { a : 1 } == { a : 1 } give an error, and ({a : 1}) == {a : 1} will work?
This is done in Firebug:
>>> {a : 1} == {a : 1}
SyntaxError: syntax error
[Break On This Error] {a : 1} == {a : 1}
>>> ({a :开发者_如何转开发 1}) == {a : 1}
false
So it needs to be ({a : 1}) == {a : 1}
, why is that?
Because {a : 1}
is a declaration and it's not allowed to be follow by ==
however
({ a : 1 })
is an expression and is allowed to be followed by ==
This is basically the rules defined in the grammer.
However note that ({ a: 1} == { a: 1})
is valid. So the equivalence expression is valid.
This means that {a : 1} == { a : 1 }
is simply not a valid statement.
12.4 of the ES5.1 spec says
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.
As a sidenote you will find that
({a : 1}) != {a : 1}
because they are two new objects
The leading "{" character is interpreted by the parser as starting a block of statements, not as starting an expression. It's an ambiguity in the language and that's the way it's resolved (according to the spec).
It's similar to the ambiguity around the function
keyword. When a statement starts with function
, it's a function declaration statement, even though syntactically it might be intended as the start of an expression. Parsers simply must resolve such ambiguities according to some rules.
I think you might want to assign both objects to variables first and compare those two variables instead of creating them within the statement. Your problem relies in the fact that you are assigning in the statement. By adding the () you are wrapping that assignment as a statement and it works fine.
精彩评论