简体   繁体   English

`2 == {}`和`{} == 2`之间有什么区别?

[英]What's difference between `2 == {}` and `{} == 2`

When I type 2 == {} on Chrome developer tools, it will return false , but when I type {} == 2 , I get a Error Uncaught SyntaxError: Unexpected token == . 当我在Chrome开发者工具上键入2 == {}时,它将返回false ,但是当我输入{} == 2 ,我会收到错误Uncaught SyntaxError: Unexpected token ==错误Uncaught SyntaxError: Unexpected token == What's hell == have done? 怎么了==做了什么?

{ is syntactically ambiguous. {在句法上是模棱两可的。 It is used in expressions (object literal syntax, {foo: 42, bar: "hello"} ) and in statements (block, { foo(); bar(); baz(); } ). 它用在表达式(对象文字语法, {foo: 42, bar: "hello"} )和语句中(块, { foo(); bar(); baz(); } )。

If a { occurs at the beginning of a statement, it is always parsed as the start of a block. 如果{发生在语句的开头,它总是被解析为块的开头。

Thus 从而

{} == 2

parses as 解析为

{
    // empty block
}
== 2  // syntax error

On the other hand, in 2 == {} , the { appears in the middle of an expression and is treated as an object. 另一方面,在2 == {}{出现在表达式的中间并被视为对象。

This is also how you can make {} == 2 work: Just make sure the { is not the first token, which you can do by eg writing ({}) == 2 or ({} == 2) . 这也是你如何使{} == 2工作:只要确保{不是第一个令牌,你可以通过写({}) == 2({} == 2)来做。

You might wrap it in parentheses to distinguish from a block statement . 您可以将其包装在括号中以区别于块语句 Then you get an epression . 然后你得到了一个表象

({} === 2)

if you write {} in javascript, it implies object. 如果你在javascript中写{},它意味着对象。 You can declare object in braces {}. 您可以在大括号{}中声明对象。 so {} == 2 or 2=={} is same.and in this case , both statment return false. 所以{} == 2或2 == {}是相同的。在这种情况下,两个statment都返回false。

In javascript, an object is a value in memory which is referenced by an identifier. 在javascript中,对象是内存中由标识符引用的值。
Primitive values can be compared with other types but when you try to compare an undeclared object, it can't be compared as there is no identifier to it. 可以将原始值与其他类型进行比较,但是当您尝试比较未声明的对象时,由于没有标识符,因此无法进行比较。 If you first declare it : 如果你第一次声明它:

var object ={};
object == 2;

This returns false because now there is an identifier to the object being referenced. 这返回false因为现在有一个被引用对象的标识符。 When you don't declare it, it acts as a block. 当你没有声明它时,它就像一个块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM