js相等比较算法
tanhui 6/1/2021
js
js相等比较算法
1.严格相等 (===)
比较 x === y:
- If Type(x) is different from Type(y), return false
- If Type(x) is Undefined, return true
- If Type(x) is Null, return true
- If Type(x) is Number, then
- If x is NaN, return false
- If y is NaN, return false
- If x is the same Number value as y, return true
- If x is +0 and y is −0, return true
- If x is −0 and y is +0, return true
- Return false
- If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false
- If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false
- Return true if x and y refer to the same object. Otherwise, return false
2. 非严格相等 (==)
比较 x == y:
- If Type(x) is the same as Type(y) , then
- If Type(x) is Undefined, return true.
- If Type(x) is Null, return true.
- If Type(x) is Number, then
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0 and y is −0, return true.
- If x is −0 and y is +0, return true.
- Return false.
- If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
- If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
- Return true if x and y refer to the same object. Otherwise, return false.
- If x is null and y is undefined, return true.
- If x is undefined and y is null, return true.
- If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
- If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
- If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
- If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
- If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
- If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
- Return false.
这个算法中有个比较重要的求值算法 toPrimitive,这是一个内部方法,用来计算对象类型的原始值,也就是将object类型转换为非object类型,用法:toPrimitive(x,prefferedType?)
,其中x
为输入值,prefferedType
为可选参数,表明想转换为的类型(string 或者 number),在不传递此参数情况下,默认认为是需要转出number类型值。
求值过程如下:
- prefferedType ?= number
- 尝试调用
x.valueOf
方法,如果该方法存在,且结果值是一个原始值,则返回该值 - 尝试调用
x.toString
方法,如果该方法存在,且结果值是一个原始值,则返回该值 - 抛出
TypeError
异常
- 尝试调用
- prefferedType = string
- 尝试调用
x.toString
方法,如果该方法存在,且结果值是一个原始值,则返回该值 - 尝试调用
x.valueOf
方法,如果该方法存在,且结果值是一个原始值,则返回该值 - 抛出
TypeError
异常
- 尝试调用
3.同值相等(Object.is)
Object.is(x, y)
比较两值是否相同
规则如下:
- x, y类型都为
undefined
,true - x, y类型都为
null
,true - x, y类型都为
string
,且长度和字符以及顺序一致,true - x, y类型都为引用类型,并且引用都是内存中同一个对象,true
- x, y类型都为number
- x, y都为 +0,true
- x, y都为 -0,true
- x, y都为 NaN, true
- x, y都为非零和非NaN的值,且值相同, true
- false