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

Ternary operator strange behavior while doing comparison of number

基本上下面的代码是对 rowind 变量进行比较并显示警报,但不知何故它输出为非零,即使它为零,然后它也输出为 "Not Zero",任何人都可以告诉我什么这可能是原因吗?

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

比较是在字符串之间进行,'0' 不等于 ''。

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

您正在检查变量 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

Equality (==)

The equality operator converts the operands if they are not of the same > type, then applies strict comparison. If both operands are objects, then > JavaScript compares internal references which are equal when operands > refer to the same object in memory.

以上解释了 == 运算符在 javascript 中的工作原理。

在您的示例中,'' 被转换为数字,因为它正在与类型数字变量进行比较。所以 javascript 将 '' 视为一个数字并且 '' 等于 0。因此 returns 在您的条件下为真。

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
0 == '' returns true in javascript

左操作数是数字类型。 右操作数是字符串类型。

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

0 == Number('')

这导致

0 == 0  // which definitely is true

是的

0 === '' will return false

与 一样,恒等运算符===不进行类型强制,因此比较时不转换值。