如何在JavaScript中检查NaN是否为NaN?

NaN 是唯一不等于其自身的值。如果我们检查 其他值,则它们等于自己,但值NaN 不等于自身。

示例1

<html>
<body>
   <script>
      var val = 54/"the";
      document.write(val);
      document.write("</br>");
      if(val == NaN) {
         document.write("NaN is equal to NaN");
      }
      else {
         document.write("check in another way");
      }
   </script>
</body>
</html>

输出结果

NaN
check in another way

在某些情况下,我们必须使用特定条件。在那些条件下,可能存在有关NaN的条件,即NaN 是否为NaN。因此,有必要建立有关NaN的条件。为了达到这种条件,ES6已经出现。它提供了Object.is()来检查NaN是否为NaN。 

示例2

<html>
<body>
<script>
   var val = 54/"the";
   document.write(val);
   document.write("</br>");
   document.write(Object.is(val,NaN));
</script>
</body>
</html>

输出结果

NaN
true