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

前端 未结 30 2979
伪装坚强ぢ
伪装坚强ぢ 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
    2020-11-22 06:36

    I just came across this technique in the book Effective JavaScript that is pretty simple:

    Since NaN is the only JavaScript value that is treated as unequal to itself, you can always test if a value is NaN by checking it for equality to itself:

    var a = NaN;
    a !== a; // true 
    
    var b = "foo";
    b !== b; // false 
    
    var c = undefined; 
    c !== c; // false
    
    var d = {};
    d !== d; // false
    
    var e = { valueOf: "foo" }; 
    e !== e; // false
    

    Didn't realize this until @allsyed commented, but this is in the ECMA spec: https://tc39.github.io/ecma262/#sec-isnan-number

提交回复
热议问题