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

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

    NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this

    var nanValue = NaN;
    if(nanValue !== nanValue) // Returns true!
        alert('nanValue is NaN');
    

    This returns true only for NaN values and Is a safe way of testing. Should definitely be wrapped in a function or atleast commented, because It doesnt make much sense obviously to test if the same variable is not equal to each other, hehe.

提交回复
热议问题