===(严格相等)在不进行转换的情况下比较值和类型。==(宽松相等)首先执行类型强制转换,这会导致令人惊讶的结果。
js
0 == "0"; // true — "0" coerced to 0
0 == ""; // true — "" coerced to 0
0 == false; // true — false coerced to 0
null == undefined; // true — special rule
"" == ;
=== ;
=== ;
为什么 == 很危险
类型强制转换规则不明显,会导致 bug。例如,[] == ![] 是 true(一个臭名昭著的怪癖)。在比较时,你很少希望 JavaScript 在你背后默默地转换类型。
规则
总是使用 ===(和 !==)。唯一常见的、有意的例外是同时检查 null 或 undefined:
js
if (value == null) { ... } // true for BOTH null and undefined — a deliberate idiom
对于其他所有情况,严格相等使比较结果可预测。要比较对象,需要进行深度相等检查(它们按引用比较,所以 {a:1} === {a:1} 是 false)。
