Javascript中==和!=的规则?

timeofsunrise
  • 1.5k

下面整理的这个表有什么问题吗?

注:Primitive()代表valueOf()|toString()
image.png

比如:'1' == new Number(1) 会先调用new Number(1)valueOf,如果可以直接做全等比较就直接做,如果不行就再调用toString()转为字符串做全等,如果还不行,就将‘1’toString后的字符串转为数字再比较,不全等就为false,全等就为true

我的理解对吗?


下面是小于(<)、大于(>)、小于等于(<=)和大于等于(>=)这几个关系操作符的隐式转换规则,也贴出来了,辛苦大家看一下,有问题,请指出,感谢!
image.png

回复
阅读 1.5k
4 个回答

==

The comparison x==y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is the same as Type(y), then

    1. Return the result of performing Strict Equality Comparison x===y.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).
  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) ==y.
  6. If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) ==y.
  7. If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
  8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x==ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) ==y.
  10. Return false.

== 会隐式转换类型
=== 类型和值完全相同 才是全等
image.png

JavaScript权威指南第74页“相等和不等运算符”这一节有介绍

宣传栏