Javascript isNaN() 函数

isNaN()函数简介

在JavaScript中使用isNaN()函数来判断一个值是否是NaN值。如果该值为非数字值或NaN值,返回true,否则返回false。那什么叫NaN值呢?啊,很简单:

NaN = "Not a Number"(非数字值)

顾名而思义,现在大家都懂了什么叫NaN值吧。其实数字型数据(整型或浮点型)就不是NaN值,而非数字型(如字符串)就是NaN值。

语法:

isNaN(参数)

说明:

这里的参数可以是任何类型的数据,例如数字型、字符串型、日期时间型等。不过得注意一点,当参数是“字符串类型的数字”,就会自动转换为数字型。

例如:

123 //这不是NaN值
"123"  //这也不是NaN值,因为“字符串类型的数字”会被自动转换为数字型
"abc123"  //这是NaN值

举例1:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        document.write("isNaN (123)的执行结果是:");
        document.write(isNaN (123)+"<br/>");
        document.write("isNaN (3.1415)的执行结果是:");
        document.write(isNaN (3.1415)+"<br/>");
        document.write("isNaN (0)的执行结果是:");
        document.write(isNaN (0)+"<br/>");
        document.write("isFinite(\"码农教程\")的执行结果是:");
        document.write(isFinite("码农教程")+"<br/>");
        document.write("isFinite(2015/05/03)的执行结果是:");
        document.write(isFinite(2015/05/03)+"<br/>");
    </script>
</head>
<body>
</body>
</html>

在浏览器预览效果如下:

Javascript isNaN() 函数

使用这个函数的典型情况就是检查parseInt()方法和parseFloat()方法的返回值。还有一种方法,便利可以与它自身进行比较,如果比较的结果不相等,那么它就是NaN。这是因为NaN是唯一与自身不等的值。

举例:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        var str1 = "test";  
        var str2 = "test123"
        var str3 = "5/0";  
  
        str1 = parseInt(str1);  
        str2 = parseInt(str2);  
        str3 = parseInt(str3);  
   
        document.write("str1 = "+ str1 + "<br>");  
        document.write("str2 = " + str2 + "<br>");  
        document.write("str3 = " + str3 + "<br>");  
   
        if (isNaN(str1) == true) {  
            document.write("str1=" + str1 + " is not a number<br>");  
        }  
        if (isNaN(str2) == true) {  
            document.write("str2=" + str2 + " is not a number<br>");  
        }  
        if (isNaN(str3) == true) {  
            document.write("str3="+ str3 + " is not a number<br>");  
        }  
    </script>
</head>
<body>
</body>
</html>

在浏览器预览效果如下:

Javascript isNaN() 函数