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

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

    I just want to share another alternative, it's not necessarily better than others here, but I think it's worth looking at:

    function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
    

    The logic behind this is that every number except 0 and NaN are cast to true.

    I've done a quick test, and it performs as good as Number.isNaN and as checking against itself for false. All three perform better than isNan

    The results

    customIsNaN(NaN);            // true
    customIsNaN(0/0);            // true
    customIsNaN(+new Date('?')); // true
    
    customIsNaN(0);          // false
    customIsNaN(false);      // false
    customIsNaN(null);       // false
    customIsNaN(undefined);  // false
    customIsNaN({});         // false
    customIsNaN('');         // false
    

    May become useful if you want to avoid the broken isNaN function.

提交回复
热议问题