先来看一个简单的题目。
var a = "42";
var a = 42;
a == b; //true
显而易见,a==b为true。可是,你再仔细想一想,通过强制转换a==b可以有两种方式给出true。这个比较要么最终成为42==42,要么成为”42”==”42”。于是问题来了,到底是哪一种呢?
答案:“42”变成42,于是比较成为42==42。在一个这样简单的例子中,只要最终结果是一样的,处理的过程走哪一条路似乎并不重要。但在一些复杂的情况下,这不仅对比较的结果很重要,而且对你如何得到这个结果也很重要。
就x==y而言,我查阅了ECMA文档,整理如下:
- 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.
是不是很清楚了呢?