2009-09-23 42 views
2

我们使用外部API,当Javascript似乎找到两者相等时,返回''或布尔值false。 例如:''等于false?区分''和布尔错误的最安全的方法是什么?

var x = ''; 
if (!x) { 
    alert(x); // the alert box is shown - empty 

} 
if (x=='') { 
    alert(x); // the alert box is shown here too - empty 

} 
var z = false; 
if (!z) { 
    alert(z); // the alert box is shown - displays 'false' 

} 
if (z=='') { 
    alert(z); // the alert box is shown here too - displays 'false' 

} 

我们如何区分这两个?

回答

27

使用三重等于

if (x===false) //false as expected 
if (z==='') //false as expected 

双等于会做类型转换,而三重等于不会。所以:

0 == "0" //true 
0 === "0" //false, since the first is an int, and the second is a string 
0
由peirix提到

:特里普尔等号同时检查值和

1 == '1' // true 
1 === '1' // false 
+3

正如您所提到的那样,之前已经提到过。为什么再提一次? – 2009-09-23 13:57:55

+0

因为当时我发布这个,他没有提及它检查值AND类型... – NDM 2009-09-23 14:14:01

2
var typeX = typeof(x); 
var typeZ = typeof(z); 

if (typeX == 'string' && x == '') 
else if (typeX == 'boolean' && !typeX) 

我喜欢Peirix的回答也一样,但这里是一个另类。

0

为避免此问题,请使用jslint验证程序。它有助于发现不安全的操作。

相关问题