admin管理员组文章数量:1391937
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?
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?
3 Answers
Reset to default 16Because {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.
本文标签: In JavaScriptwhy doesa1a1give an errorand (a1)a1 will workStack Overflow
版权声明:本文标题:In Javascript, why does { a : 1 } == { a : 1 } give an error, and ({a : 1}) == {a : 1} will work? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738747905a2110228.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论