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

!= 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.

 

 


 

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

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

 

==nullundified''false0
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);

检验.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值