‘==’的操作原理
让我们来看看undefined ,null,0之间的爱恨情仇。
先上结果:
null == 0 //false
undefined ==0 //false
undefined ==null //true
就很离谱吧!!!
相等:==[运算符]用于比较两个值,返回true或false。
“The comparison x == y, where x and y are values, produces true or false.”
ReturnIfAbrupt(x).
ReturnIfAbrupt(y).
If Type(x) is the same as Type(y), then Return the result of
performing Strict Equality Comparison x === y.
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, Number, or Symbol and Type(y) is Object,
then return the result of the comparison x == ToPrimitive(y).
If Type(x) is Object and Type(y) is either String, Number, or Symbol,
then return the result of the comparison ToPrimitive(x) == y.
Return false.
一共有12步骤:
如果x不是正常值(比如抛出一个错误),中断执行。
如果y不是正常值,中断执行。
如果Type(x)与Type(y)相同,执行严格相等运算x === y。
如果x是null,y是undefined,返回true。
如果x是undefined,y是null,返回true。
如果Type(x)是数值,Type(y)是字符串,返回x == ToNumber(y)的结果。
如果Type(x)是字符串,Type(y)是数值,返回ToNumber(x) == y的结果。
如果Type(x)是布尔值,返回ToNumber(x) == y的结果。
如果Type(y)是布尔值,返回x == ToNumber(y)的结果。
如果Type(x)是字符串或数值或Symbol值,Type(y)是对象,返回x == ToPrimitive(y)的结果。
如果Type(x)是对象,Type(y)是字符串或数值或Symbol值,返回ToPrimitive(x) == y的结果。
返回false。
总结:
x和y有一个不是正常值,中断执行
x和y类型相同,执行全等===
null和undefined,结果是true
数值和字符串比较,把字符转换成数值,再进行比较
其中有一个是布尔值,把布尔值转换成0和1,再进行比较
其中有一个是对象,先拆箱,再进行比较
没有符合上述的直接返回false,例如:undefined == 0 返回false