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

前端 未结 30 2623
伪装坚强ぢ
伪装坚强ぢ 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:34

    If your environment supports ECMAScript 2015, then you might want to use Number.isNaN to make sure that the value is really NaN.

    The problem with isNaN is, if you use that with non-numeric data there are few confusing rules (as per MDN) are applied. For example,

    isNaN(NaN);       // true
    isNaN(undefined); // true
    isNaN({});        // true
    

    So, in ECMA Script 2015 supported environments, you might want to use

    Number.isNaN(parseFloat('geoff'))
    
    0 讨论(0)
  • 2020-11-22 06:34

    Found another way, just for fun.

    function IsActuallyNaN(obj) {
      return [obj].includes(NaN);  
    }
    
    0 讨论(0)
  • 2020-11-22 06:35

    The exact way to check is:

    //takes care of boolen, undefined and empty
    
    isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
    
    0 讨论(0)
  • 2020-11-22 06:36

    I just came across this technique in the book Effective JavaScript that is pretty simple:

    Since NaN is the only JavaScript value that is treated as unequal to itself, you can always test if a value is NaN by checking it for equality to itself:

    var a = NaN;
    a !== a; // true 
    
    var b = "foo";
    b !== b; // false 
    
    var c = undefined; 
    c !== c; // false
    
    var d = {};
    d !== d; // false
    
    var e = { valueOf: "foo" }; 
    e !== e; // false
    

    Didn't realize this until @allsyed commented, but this is in the ECMA spec: https://tc39.github.io/ecma262/#sec-isnan-number

    0 讨论(0)
  • 2020-11-22 06:37

    It seems that isNaN() is not supported in Node.js out of the box.
    I worked around with

    var value = 1;
    if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
    
    0 讨论(0)
  • 2020-11-22 06:38

    Try this code:

    isNaN(parseFloat("geoff"))
    

    For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?

    0 讨论(0)
提交回复
热议问题