为什么{}!=({})在JavaScript中? [英] Why {} != ( {} ) in JavaScript?

查看:205
本文介绍了为什么{}!=({})在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知, {} 是定义像 [] 这样的对象的较短方式。

It's commonly known that {} is shorter way to define an object like [] is for an array.

但现在我想知道原因:

{} != ({})




  • {} 评估为未定义

  • ({})评估为更正对象

    • {} evaluates to undefined
    • ({}) evaluates to "correct" Object
    • 为什么JavaScript的行为如此?

      Why is JavaScript behaving like this ?

      例如 1 等于(1),为什么 {} 不等于({ })

      For example 1 equals to (1), so why {} not equals to ({}) ?

      推荐答案

      {} != ({})
      

      这是语法错误。

      SyntaxError:意外的令牌!=

      SyntaxError: Unexpected token !=

      {} 是这样的暧昧。它是空块还是空对象文字?它失败了,因为比较运算符不能跟随块。

      {} is ambigious like that. Is it an empty block, or an empty object literal? It's failing because a comparison operator can not follow a block.

      用括号括起来使解析器将其视为表达式。表达式不能包含块,因此它知道它是一个对象。

      Wrapping it with parenthesis makes the parser treat it as an expression. An expression can't contain a block, so it knows it's an object.

      但是,如果将该比较包装在表达式中...

      However, if you wrap that comparison in an expression...

      ({} != ({}))
      

      ...它仍然是正确的,因为具有分配给它们的值的对象的变量是它们的指针,因此,它们永远不会被它们的内容复制(尽管这与你的例子无关)。因此,它们的指针始终不同,并且比较失败。

      ...it's still true because variables which have an object assigned to them's values are a pointer to them and as a consequence, they are never copied around by their contents (though this is irrelevant to your example). Because of this, their pointer is always different and the comparison fails.

      这也意味着比较指向同一对象的两个变量将按预期工作,作为它们的指针将是相同的。

      This also implies that comparing two variables which point to the same object will work as expected, as their pointers will be the same.

      这篇关于为什么{}!=({})在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆