''在Javascript中等于false?区分''和布尔假的最安全的方法是什么?

Sag*_*chi 2 javascript

我们使用外部API whcih返回''或布尔值假,而Javascript似乎找到两者相等.例如:

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'

}
Run Code Online (Sandbox Code Playgroud)

我们如何区分这两者?

pei*_*rix 28

使用三倍相等

if (x===false) //false as expected
if (z==='') //false as expected
Run Code Online (Sandbox Code Playgroud)

双等于将进行类型转换,而三等于不进行类型转换.所以:

0 == "0" //true
0 === "0" //false, since the first is an int, and the second is a string
Run Code Online (Sandbox Code Playgroud)