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

>>> "0" == false
true

>>> false == "0"
true

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

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

当前回答

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/

其他回答

这是按规格的。

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运算,请使用===(也称为“严格”相等运算符)

在PHP中,字符串“0”是假的(false-when-used-in-boolean-context)。在JavaScript中,所有非空字符串都是真值。

技巧是==针对布尔值并不在布尔上下文中求值,它转换为数字,在字符串的情况下是通过解析为十进制来完成的。所以你得到0而不是truthiness boolean true。

这是一个非常糟糕的语言设计,这也是我们尽量不使用不幸的==操作符的原因之一。请使用===代替。

The "if" expression tests for truthiness, while the double-equal tests for type-independent equivalency. A string is always truthy, as others here have pointed out. If the double-equal were testing both of its operands for truthiness and then comparing the results, then you'd get the outcome you were intuitively assuming, i.e. ("0" == true) === true. As Doug Crockford says in his excellent JavaScript: the Good Parts, "the rules by which [== coerces the types of its operands] are complicated and unmemorable.... The lack of transitivity is alarming." It suffices to say that one of the operands is type-coerced to match the other, and that "0" ends up being interpreted as a numeric zero, which is in turn equivalent to false when coerced to boolean (or false is equivalent to zero when coerced to a number).

// I usually do this:

x = "0" ;

if (!!+x) console.log('I am true');
else      console.log('I am false');

// Essentially converting string to integer and then boolean.
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/