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

>>> "0" == false
true

>>> false == "0"
true

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

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

当前回答

这都是因为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

其他回答

在JS中,“==”符号不检查变量的类型。因此,“0”= 0 = false(在JS中为0 = false),在这种情况下将返回true,但如果使用“===”,结果将为false。

当你使用"if"时,在以下情况下它将是"false":

[0, false, '', null, undefined, NaN] // null = undefined, 0 = false

So

if("0") = if( ("0" !== 0) && ("0" !== false) && ("0" !== "") && ("0" !== null) && ("0" !== undefined) && ("0" !== NaN) )
        = if(true && true && true && true && true && true)
        = if(true)

显示问题的表格:

和= =

这个故事的寓意使用===

表生成credit: https://github.com/dorey/JavaScript-Equality-Table

0周围的引号使它成为一个字符串,它的值为true。

删除引号,它应该工作。

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

原因是,当显式执行"0" == false时,两边都被转换为数字,然后执行比较。

如果执行:if ("0") console.log("ha"),则正在测试字符串值。任何非空字符串为真,而空字符串为假。

Equal (==) If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory. (From Comparison Operators in Mozilla Developer Network)

==相等运算符在将参数转换为数字后求值。 因此字符串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是假的

`