NaN 比较 returns 对吗?

NaN comparison returns true?

最近几天我阅读了 NaN 如何始终将 false 与自身进行比较,以及如何比较可能出现 NaN 的东西,现在我制作了一个 JS 来比较两个 NaN true。什么鬼?还是我比较了 'NaN' 个字符串?

http://www.bksys.at/bernhard/JS-NaN-compare-true.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>radioactivity calculator</title>
</head>

<body>

<form name="form1">
a: <input type="text" name="a"><br>
b: <input type="text" name="b"><br>
x: <input type="text" name="x"><br>

</form>

<script type="text/javascript">

    document.form1.a.value=Math.sqrt(-1);
    document.form1.b.value=(1/0)/(1/0);
    document.form1.x.value=(document.form1.a.value==document.form1.b.value);

</script>

</body>
</html>

您确实是在将字符串 "NaN" 与另一个字符串 "NaN" 进行比较,后者等于 true。文本 input 元素中的 value 始终作为字符串类型提取。

解决这个问题的一个简单方法是在您的值前面加上 Unary Plus (+) operator 以将它们转换为整数值(您也可以去掉这些括号):

document.form1.x.value = +document.form1.a.value == +document.form1.b.value;

例子

document.form1.a.value = Math.sqrt(-1);
document.form1.b.value = (1/0) / (1/0);
document.form1.x.value = +document.form1.a.value == +document.form1.b.value;
<form name="form1">
  a: <input  type="text" name="a" size="20" value="a"><br>
  b: <input  type="text" name="b" size="20" value="b"><br>
  x: <input  type="text" name="x" size="20" value="x"><br>
</form>


注意: 正如 RobG 在他下面的评论中指出的,这里需要注意的是,将字符串值 "NaN" 转换为整数一元加运算符将其直接转换为 NaN,因为该字符串无法复制为数值。如果您的两个 input 元素都包含值 "Foo",甚至包含两个完全不同的非数字字符串值,也会发生同样的情况。虽然此解决方案确实有效,但如果您要扩展此代码以处理非数字值,它可能会产生意外结果。

这是一个 JavaScript 陷阱 ;)

比较 NaN 的正确方法是使用 isNaN 方法。

var a = 'a' + 5; //NaN

if (isNaN(a)) {
    //do something
}

NaN是JavaScript中的一个特殊值。它甚至不等于自己(也是一种快速测试方法):

var a = parseInt('seven');
if (a == a) {
    alert("a == a"); 
} else {
    alert("a != a"); // This will happen
}
if (a == 'NaN') {
    // Won't happen
} else {
    alert("NaN is not equal to the string 'NaN'"); // Here
} 

http://jsfiddle.net/u951v90o/