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

>>> "0" == false
true

>>> false == "0"
true

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

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

当前回答

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

"100" == 100

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

"100" === 100

检查值和数据类型

其他回答

显示问题的表格:

和= =

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

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

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

我也有同样的问题,我找到了一个可行的解决方案如下:

原因是

    if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN

永远不要使用id之类的数字类型

      if (id) {}

对于可能值为0的id类型,我们不能使用if (id){},因为if(0)将意味着false,无效,这是我们想要的,它意味着有效为true id数。

所以对于id类型,我们必须使用以下方法:

   if ((Id !== undefined) && (Id !== null) && (Id !== "")){
                                                                                
                                                                            } else {

                                                                            }
                                                                            

对于其他字符串类型,我们可以使用if (string){},因为null, undefined,空字符串都将计算为false,这是正确的。

       if (string_type_variable) { }

在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).