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

>>> "0" == false
true

>>> false == "0"
true

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

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

当前回答

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

其他回答

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

显示问题的表格:

和= =

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

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

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

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

原因是

    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) { }
// 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.