使用 `!=` 和 `==` 比较对象和布尔值有不同的结果
Compare Object and Boolean has different results using `!=` and `==`
我无法理解 JavaScript 中相等运算符的行为。这是我在浏览器控制台上 运行 以下命令时得到的结果:
new Object() == true // returns false
new Object() != false // returns true
现在,我不同意 Object 应该是 false 的事实(虽然我在检查 ECMAScript Language Specification 后理解了 为什么 ),但真正的是什么困扰我的是我在两个等价的逻辑表达式上得到了两个不同的结果。
发生了什么事?
您链接到 this,它根据左侧和右侧的内容给出了 10 个要检查的步骤列表。
左边是一个对象。右侧是布尔值。
这意味着它到达第 10 步:
Return false.
对象不等于 true
也不等于 false
。
根据规范,这两个都应该 return false
(这符合我的常识):
new Object() == true // false
new Object() == false // false
基于:
If Type(x) is Object and Type(y) is either String or Number,
return the result of the comparison ToPrimitive(x) == y.
Return false.
因为它们都是 return false 并且:
A != B is equivalent to !(A == B).
这两个都应该是true
:
new Object() != true // true
new Object() != false // true
注:
这不应与 new Object()
的 真实性 相混淆。换句话说 new Object() == true
是不一样的 Boolean(new Object()) == true
我无法理解 JavaScript 中相等运算符的行为。这是我在浏览器控制台上 运行 以下命令时得到的结果:
new Object() == true // returns false
new Object() != false // returns true
现在,我不同意 Object 应该是 false 的事实(虽然我在检查 ECMAScript Language Specification 后理解了 为什么 ),但真正的是什么困扰我的是我在两个等价的逻辑表达式上得到了两个不同的结果。
发生了什么事?
您链接到 this,它根据左侧和右侧的内容给出了 10 个要检查的步骤列表。
左边是一个对象。右侧是布尔值。
这意味着它到达第 10 步:
Return false.
对象不等于 true
也不等于 false
。
根据规范,这两个都应该 return false
(这符合我的常识):
new Object() == true // false
new Object() == false // false
基于:
If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
Return false.
因为它们都是 return false 并且:
A != B is equivalent to !(A == B).
这两个都应该是true
:
new Object() != true // true
new Object() != false // true
注:
这不应与 new Object()
的 真实性 相混淆。换句话说 new Object() == true
是不一样的 Boolean(new Object()) == true