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

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

    I wrote this answer to another question on StackOverflow where another checks when NaN == null but then it was marked as duplicate so I don't want to waste my job.

    Look at Mozilla Developer Network about NaN.


    Short answer

    Just use distance || 0 when you want to be sure you value is a proper number or isNaN() to check it.

    Long answer

    The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed.

    You wanted to check if NaN == null which results false. Hovewer even NaN == NaN results with false.

    A Simple way to find out if variable is NaN is an global function isNaN().

    Another is x !== x which is only true when x is NaN. (thanks for remind to @raphael-schweikert)

    But why the short answer worked?

    Let's find out.

    When you call NaN == false the result is false, same with NaN == true.

    Somewhere in specifications JavaScript has an record with always false values, which includes:

    • NaN - Not-a-Number
    • "" - empty string
    • false - a boolean false
    • null - null object
    • undefined - undefined variables
    • 0 - numerical 0, including +0 and -0

提交回复
热议问题