最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

In Javascript, why does { a : 1 } == { a : 1 } give an error, and ({a : 1}) == {a : 1} will work? - Stack Overflow

programmeradmin5浏览0评论

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?

Share Improve this question asked Oct 10, 2011 at 13:42 nonopolaritynonopolarity 151k141 gold badges489 silver badges781 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 16

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论