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

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

    While @chiborg 's answer IS correct, there is more to it that should be noted:

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

    Point being, if you're using this method for validation of input, the result will be rather liberal.

    So, yes you can use parseFloat(string) (or in the case of full numbers parseInt(string, radix)' and then subsequently wrap that with isNaN(), but be aware of the gotcha with numbers intertwined with additional non-numeric characters.

提交回复
热议问题