Why is isNaN(null) == false in JS?

后端 未结 8 1428
迷失自我
迷失自我 2020-11-28 05:07

This code in JS gives me a popup saying \"i think null is a number\", which I find slightly disturbing. What am I missing?

8条回答
  •  清酒与你
    2020-11-28 05:47

    This is indeed disturbing. Here is an array of values that I tested:

    var x = [undefined, NaN, 'blah', 0/0, null, 0, '0', 1, 1/0, -1/0, Number(5)]
    

    It evaluates (in the Firebug console) to:

    ,NaN,blah,NaN,,0,0,1,Infinity,-Infinity,5
    

    When I call x.map(isNaN) (to call isNaN on each value), I get:

    true,true,true,true,false,false,false,false,false,false,false
    

    In conclusion, isNaN looks pretty useless! (Edit: Except it turns out isNaN is only defined over Number, in which case it works just fine -- just with a misleading name.)

    Incidentally, here are the types of those values:

    x.map(function(n){return typeof n})
    -> undefined,number,string,number,object,number,string,number,number,number,number
    

提交回复
热议问题