代码之家  ›  专栏  ›  技术社区  ›  Sagar Shirke

三元运算符在进行数字比较时的奇怪行为

  •  0
  • Sagar Shirke  · 技术社区  · 11 年前

    基本上,下面的代码是对rowind变量进行比较并显示警告,但不知为何,即使输出为零,它也会输出为“非零”,有人能告诉我这是什么原因吗?

    <head>
        <script language="javascript" type="text/javascript">
    
         var rowind = 0;
        var newind = ((rowind == '')) ? "Blank" : "Some number";
    
        //Output is Blank
        alert(newind);
    
        </script>
    </head>
    <body>
    </body>
    </html>
    
    3 回复  |  直到 11 年前
        1
  •  1
  •   Community Mohan Dere    6 年前

    您正在检查变量 rowind 等于条件中的空字符串。

    ((rowind == '')) // this will return as false since you variable is not an empty string. Rather it contains a string with 0 character
    

    如果要比较字符串,请使用以下命令。

    ((rowind == '0')) //This will return true since the string is as same as the variable.
    

    使现代化

    您所问的问题与javascript类型转换有关。

    The MDN Doc

    相等(==)

    如果操作数不是相同的>类型,然后应用严格的比较。如果两个操作数都是对象,则>当操作数>引用内存中的同一对象。

    以上说明了 == 运算符在javaascript中工作。

    在您的示例中 '' 因为它与类型号变量进行比较。所以javascript处理 '' 作为数字和 '' 等于0。因此在您的条件下返回true。

    console.log(0 == '0');  //True
    console.log(0 == '');   //True
    console.log('' == '0'); //False
    

    以下是 strict comparison 作为示例。

    console.log(3 == '3') //True
    console.log(3 === '3') //False
    
        2
  •  1
  •   Vibhesh Kaul    11 年前
    0 == '' returns true in javascript
    

    左操作数的类型为Number。 右操作数的类型为String。

    在这种情况下,右操作数被强制为类型Number:

    0 == Number('')
    

    这导致

    0 == 0  // which definitely is true
    

    是的

    0 === '' will return false
    

    作为身份运算符 === 不执行类型强制,因此在比较时不转换值。

        3
  •  0
  •   Ori Drori    11 年前

    字符串之间存在比较,并且“0”不等于“”。

    因为“0”!=“”不会将它们中的任何一个转换为布尔值,因为它们的类型相同-字符串。