如下所示,Javascript中的"0"为false:

>>> "0" == false
true

>>> false == "0"
true

那么下面为什么打印“哈”呢?

>>> if ("0") console.log("ha")
ha

当前回答

我从搜索中心来到这里,寻找将“0”计算为布尔值的解决方案。 上面已经解释了技术细节,所以我不会深入讨论它,但我发现一个快速的类型转换解决了它。

因此,如果有人像我一样,想要像PHP一样,将字符串1或0计算为布尔值。然后你可以做上面的一些事情,或者你可以像这样使用parseInt():

x = "0";
if(parseInt(x))
//false

其他回答

if (x) 

使用JavaScript内部的toBoolean (http://es5.github.com/#x9.2)强制x

x == false

使用内部tonnumber强制(http://es5.github.com/#x9.3)或对象的toPrimitive强制(http://es5.github.com/#x9.1)

详情见http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/

这就是为什么你应该尽可能使用严格相等===或严格相等!== =的原因

"100" == 100

为True,因为这只检查值,而不是数据类型

"100" === 100

检查值和数据类型

==相等运算符在将参数转换为数字后求值。 因此字符串0" 0"被转换为数字数据类型,布尔值false被转换为数字0。 所以

"0" == false // true

同样适用于'

False == "0" //true

===严格的相等性检查使用原始数据类型计算参数

"0" === false // false,因为"0"是字符串,false是布尔值

同样适用于

False === "0" // False

In

if(“0”) console.log(“ha”);

String "0"不与任何参数进行比较,并且String在与任何参数进行比较之前都是真值。 就像

if (true) console.log (" ha ");

But

If (0) console.log("ha");//空控制台行,因为0是假的

`

这都是因为ECMA规格…"0" == false,因为这里指定的规则http://ecma262-5.com/ELS5_HTML.htm#Section_11.9.3…if('0')的结果为true,因为这里指定的规则http://ecma262-5.com/ELS5_HTML.htm#Section_12.5

这是按规格的。

12.5 The if Statement 
.....

2. If ToBoolean(GetValue(exprRef)) is true, then 
a. Return the result of evaluating the first Statement. 
3. Else, 
....

根据规范,ToBoolean是

抽象操作ToBoolean根据表11将其参数转换为Boolean类型的值:

这个表格是这样描述字符串的:

如果参数为空String(其长度为零),则结果为假; 否则结果为真

现在,为了解释为什么"0" == false,您应该读取相等运算符,它表示它从抽象操作GetValue(lref)中获得其值,与右侧的相同。

将相关部分描述为:

if IsPropertyReference(V), then 
a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get
be the special [[Get]] internal method defined below. 
b. Return the result of calling the get internal method using base as its this value, and passing 
GetReferencedName(V) for the argument

或者换句话说,字符串有一个基元,它会回调内部的get方法,结果看起来是false。

如果你想用GetValue运算来求值,请使用==,如果你想用ToBoolean运算,请使用===(也称为“严格”相等运算符)