isNan() function in Javascript not identifying toString()

The below code is just to display "true" or "false" based on whether the input to isNaN() function is a number or not. In isNaN() function, I am converting the type of number to string using the toString() function. But still, the output I am getting is 'false' instead of 'true'

<html>

  <head>
    <title>check</title>

            <script type='text/javascript'>         

            function checkRun(){
                var obj = {
                 atr : 1,
                 prof : 'dtc'
                }           
                alert(isNaN(obj.atr.toString()));
            }

            </script>

        </title>
    </head>

    <body>    
        <input type='text' name='checkName' id='check1' value='val1' class='class1'/><br><br>
        <button type='button' name='checkName' id='check3' value='val3' class='class3' onclick='checkRun()'>Hello</button>
    </body>

</html>

obj.atr is 1 , which is a number. isNaN returns true if its input is "not a number". Another way to think of it is that isNaN returns false if its input is a number. What you are experiencing is the expected behavior.

Another thing to keep in mind: isNaN checks if the value can be interpreted as a number, not that it is stored as a number. isNaN("1234") will return false because "1234" (the string) can be converted into 1234 (the number)

If you want to check if the value is actually stored as a number, you can do typeof value === "number"


The isNaN function is the %isNaN% intrinsic object. When the isNaN function is called with one argument number, the following steps are taken:

   1. Let num be -> ToNumber(number).  /because of this toString() not consider

   2. If num is NaN, return true.

   3. Otherwise, return false.

NOTE: A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form X !== X. The result will be true if and only if X is a NaN.check Here


There are two isNaN functions.

The global isNaN function, converts the tested value to a Number, then tests it. That is why even though you had converted obj.atr to a string, it was converted back to a number and hence returned false .

Number.isNaN does not convert the values to a Number, and will not return true for any value that is not of the type Number. So, it will also return false as the type of obj.atr is string.

From what you had asked in the question, I think you can go for typeof val === number as suggested by @EKW

链接地址: http://www.djcxy.com/p/94994.html

上一篇: 数组+ charAt问题

下一篇: Javascript中的isNan()函数不能识别toString()