==
和 ===
一样,只是 ==
做类型转换。
为了让你明白我的意思,这里有一个 JavaScript 函数,它的行为与 ==
完全相同:
function loseEqual(x, y) {
if(typeof y === typeof x) return y === x;
if(typeof y === "function" || typeof x === "function") return false;
var xIsNothing = (y === undefined) || (y === null);
var yIsNothing = (x === undefined) || (x === null);
if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);
if(typeof x === "object") x = toPrimitive(x);
if(typeof y === "object") y = toPrimitive(y);
if(typeof y === typeof x) return y === x;
if(typeof x !== "number") x = +x;
if(typeof y !== "number") y = +y;
return x === y;
}
function toPrimitive(obj) {
var value = obj.valueOf();
if(obj !== value) return value;
return obj.toString();
}
这个函数应该有助于解释为什么人们一直说你不应该使用 ==
。
正如您所见,==
具有许多复杂的类型转换逻辑。因此很难预测您将得到什么结果 - 这可能导致错误。
以下是一些您不会预期到的结果示例:
意外的真相
[1] == true // returns true
'0' == false // returns true
[] == false // returns true
[[]] == false // returns true
[0] == false // returns true
'\r\n\t' == 0 // returns true
意外的结论
// IF an empty string '' is equal to the number zero (0)
'' == 0 // return true
// AND the string zero '0' is equal to the number zero (0)
'0' == 0 // return true
// THEN an empty string must be equal to the string zero '0'
'' == '0' // returns **FALSE**
具有特殊功能的对象
var objTest = {
toString: function() {
return "test";
}
};
var obj100 = {
valueOf: function() {
return 100;
}
};
var objTest100 = {
toString: function() {
return "test";
},
valueOf: function() {
return 100;
}
};
objTest == "test"
obj100 == 100
objTest100 == 100
objTest100 == "test"