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

>>> "0" == false
true

>>> false == "0"
true

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

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

当前回答

这是因为JavaScript在布尔上下文和代码中使用类型强制

if ("0") 

将在布尔上下文中被强制为true。

在Javascript中还有其他的真值,在布尔上下文中会被强制为真,因此执行if块:-

if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)

其他回答

// 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.

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

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

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

原因是,当显式执行"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周围的引号使它成为一个字符串,它的值为true。

删除引号,它应该工作。

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

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

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

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