How do you check that a number is NaN in JavaScript?

前端 未结 30 2960
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:19

I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:

parseFloat(\'geoff\') == NaN;

parseFloat(\'ge         


        
30条回答
  •  耶瑟儿~
    2020-11-22 06:39

    NaN in JavaScript stands for "Not A Number", although its type is actually number.

    typeof(NaN) // "number"
    

    To check if a variable is of value NaN, we cannot simply use function isNaN(), because isNaN() has the following issue, see below:

    var myVar = "A";
    isNaN(myVar) // true, although "A" is not really of value NaN
    

    What really happens here is that myVar is implicitly coerced to a number:

    var myVar = "A";
    isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact
    

    It actually makes sense, because "A" is actually not a number. But what we really want to check is if myVar is exactly of value NaN.

    So isNaN() cannot help. Then what should we do instead?

    In the light that NaN is the only JavaScript value that is treated unequal to itself, so we can check for its equality to itself using !==

    var myVar; // undefined
    myVar !== myVar // false
    
    var myVar = "A";
    myVar !== myVar // false
    
    var myVar = NaN
    myVar !== myVar // true
    

    So to conclude, if it is true that a variable !== itself, then this variable is exactly of value NaN:

    function isOfValueNaN(v) {
        return v !== v;
    }
    
    var myVar = "A";
    isNaN(myVar); // true
    isOfValueNaN(myVar); // false
    

提交回复
热议问题