你也许不知道的== 和 === 的判断原理

97 阅读1分钟

1.首先看看===

1.这个比较简单,首先判断两者的值和类型是否相等,类型不一致直接返回false,类型一致的情况下才去判断值是否相等

2.比较复杂的是==

ECMA规定

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  
    a. Return the result of performing Strict Equality Comparison x === y.
1.  If x is null and y is undefined, return true.
1.  If x is undefined and y is null, return true.
1.  If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
1.  If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
1.  If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
1.  If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
1.  If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
1.  If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x)== y.
1.  Return false.

==的比较原理。如果两这者的类型不同的话,会进行类型转换 比较的原理:

  • 1.如果类型相同,进行值比较

  • 2.如果是undefined和 null比较,返回的是true

  • 3.如果是string和 number进行比较,将字符串转成数字

  • 4.boolean和其他类型比较,将boolean转成数字

  • 5.一方为object,另一方为 number,string,symbol,将object转成原始值再比较。