Confusion between isNaN and Number.isNaN in javascript

前端 未结 4 1640
悲哀的现实
悲哀的现实 2020-11-29 08:13

I have a confusion in how NaN works. I have executed isNaN(undefined) it returned true . But if I will use Number.isNaN(undefined) it

4条回答
  •  一向
    一向 (楼主)
    2020-11-29 08:46

    • isNaN converts the argument to a Number and returns true if the resulting value is NaN.
    • Number.isNaN does not convert the argument; it returns true when the argument is a Number and is NaN.

    So which one i should use.

    I am guessing you are trying to check if the value is something that looks like a number. In which case the answer is neither. These functions check if the value is an IEEE-754 Not A Number. Period. For example this is clearly wrong:

    var your_age = "";
    // user forgot to put in their age
    if (isNaN(your_age)) {
      alert("Age is invalid. Please enter a valid number.");
    } else {
      alert("Your age is " + your_age + ".");
    }
    // alerts "Your age is ."
    // same result when you use Number.isNaN above

    Also why there is so discrepancy in the result.

    As explained above Number.isNaN will return false immediately if the argument is not a Number while isNaN first converts the value to a Number. This changes the result. Some examples:

                    |       Number.isNaN()       |        isNaN()
    ----------------+----------------------------+-----------------------
    value           | value is a Number | result | Number(value) | result
    ----------------+-------------------+--------+---------------+-------
    undefined       | false             | false  | NaN           | true
    {}              | false             | false  | NaN           | true
    "blabla"        | false             | false  | NaN           | true
    new Date("!")   | false             | false  | NaN           | true
    new Number(0/0) | false             | false  | NaN           | true
    

提交回复
热议问题