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

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

    Is (NaN >= 0) ?...... "I don't Know".

    function IsNotNumber( i ){
        if( i >= 0 ){ return false; }
        if( i <= 0 ){ return false; }
        return true;
    }
    

    Conditions only execute if TRUE.

    Not on FALSE.

    Not on "I Don't Know".

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

    To fix the issue where '1.2geoff' becomes parsed, just use the Number() parser instead.

    So rather than this:

    parseFloat('1.2geoff'); // => 1.2
    isNaN(parseFloat('1.2geoff')); // => false
    isNaN(parseFloat('.2geoff')); // => false
    isNaN(parseFloat('geoff')); // => true
    

    Do this:

    Number('1.2geoff'); // => NaN
    isNaN(Number('1.2geoff')); // => true
    isNaN(Number('.2geoff')); // => true
    isNaN(Number('geoff')); // => true
    

    EDIT: I just noticed another issue from this though... false values (and true as a real boolean) passed into Number() return as 0! In which case... parseFloat works every time instead. So fall back to that:

    function definitelyNaN (val) {
        return isNaN(val && val !== true ? Number(val) : parseFloat(val));
    }
    

    And that covers seemingly everything. I benchmarked it at 90% slower than lodash's _.isNaN but then that one doesn't cover all the NaN's:

    http://jsperf.com/own-isnan-vs-underscore-lodash-isnan

    Just to be clear, mine takes care of the human literal interpretation of something that is "Not a Number" and lodash's takes care of the computer literal interpretation of checking if something is "NaN".

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

    So I see several responses to this,

    But I just use:

    function isNaN(x){
         return x == x && typeof x == 'number';
    }
    
    0 讨论(0)
  • 2020-11-22 06:46

    I use underscore's isNaN function because in JavaScript:

    isNaN(undefined) 
    -> true
    

    At the least, be aware of that gotcha.

    0 讨论(0)
  • 2020-11-22 06:47
    alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);
    

    This is not elegant. but after trying isNAN() I arrived at this solution which is another alternative. In this example I also allowed '.' because I am masking for float. You could also reverse this to make sure no numbers are used.

    ("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)
    

    This is a single character evaluation but you could also loop through a string to check for any numbers.

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

    Use this code:

    isNaN('geoff');
    

    See isNaN() docs on MDN.

    alert ( isNaN('abcd'));  // alerts true
    alert ( isNaN('2.0'));  // alerts false
    alert ( isNaN(2.0));  // alerts false
    
    0 讨论(0)
提交回复
热议问题