JavaScript 为什么”0″等于false

JavaScript 为什么”0″等于false

在JavaScript中,“0”等于false,因为”0“的类型是字符串,但是当进行等于的比较时,JavaScript会进行自动类型转换,将“0”转换为其数值类型的值0,而我们知道0代表false。所以,“0”等于false。

示例: 这个示例说明了为什么”0″等于false。

<script> 
      
    // JavaScript code to demonstrate  
    // why “0” is equal to false 
      
    function GFG() { 
      
        // Print type of "0" 
        document.write(typeof "0" + "</br>"); 
      
        // Test whether "0" equals to false 
        // or not. If "0" is equal to false 
        // then "0" == false i.e. 
        // false == false which return true 
        var result = ("0" == false); 
          
        // Print result 
        document.write(result + "</br>"); 
          
        // Convert and print "0" to its numeric 
        // value 
        document.write(Number("0") + "</br>"); 
          
        // Convert and print false in numeric value 
        document.write(Number(false) + "</br>"); 
          
        // So both numeric value are same 
        // Therefore condition "0" == false 
        // evaluates to true 
        document.write("0" == false); 
        document.write("</br>"); 
          
        // Or this statement 
        document.write(Number("0") == Number(false)); 
    } 
      
    // Driver code 
    GFG(); 
      
</script> 

输出:

string
true
0
0
true
true

所以,从上面可以清楚地看出,“0”等于假,这种行为背后的原因也很明显,但是当“0”在if条件中进行测试时,它会被评估为真。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程