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

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

    As far as a value of type Number is to be tested whether it is a NaN or not, the global function isNaN will do the work

    isNaN(any-Number);
    

    For a generic approach which works for all the types in JS, we can use any of the following:

    For ECMAScript-5 Users:

    #1
    if(x !== x) {
        console.info('x is NaN.');
    }
    else {
        console.info('x is NOT a NaN.');
    }
    

    For people using ECMAScript-6:

    #2
    Number.isNaN(x);
    

    And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan

    #3
    //Polyfill from MDN
    Number.isNaN = Number.isNaN || function(value) {
        return typeof value === "number" && isNaN(value);
    }
    // Or
    Number.isNaN = Number.isNaN || function(value) {     
        return value !== value;
    }
    

    please check This Answer for more details.

提交回复
热议问题