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

前端 未结 30 2640
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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'))
    

提交回复
热议问题