!= and == vs. !== and ===

A common mistake that developers are susceptible to is the lack of understanding of false
values in JavaScript. In JavaScript, null, 0, ‘’, false, and undefined are all equal (==) to each
other, since they all evaluate to false.
This means that if you use the code test == false, it
will evaluate true if test is also undefined or equal to null, which may not be what you want.
This is where !== and === become useful. Both of these operators look at the explicit
value of the variable (such as null), not just what it is equivalent to (such as false). JSLint
requires that anytime you use != or == against a falselike value, you must use !== or ===
instead. Listing 3-12 shows some examples of how these operators differ.

 

  • Listing 3-12. Examples of How != and == Differ from !== and ===   
  • // Both of these are true
  • null == false
  • 0 == undefined   
  • // You should use !== or === instead
  • null !== false
  • false === false

上文摘自John Resig的《Pro JavaScript Techniques》,但是有些错误。

如果用==对null, undified, '', false, 0进行判断,结果并不像书上所说null == false,我对这5个值分别判断结果如下(IE7和Firefox结果一致):

== null undified '' false 0
null        
undified      
'' × ×    
false × ×
0 × ×

可以看到, null == undifed, '' == false, '' == 0, false == 0

但是null, undified, '', 0都可以在bool转化时转成false, 比如 if(null), if(undified), if(''), if('')和if(false)等效.

这点可用

document.writeln(!null);
document.writeln(!undefined);
document.writeln(!'');
document.writeln(!false);
document.writeln(!0);

检验.

你可能感兴趣的:(===)