When writing code today, ts prompts you to use Number. IsNaN instead. After the substitution, the expected result is not obtained, only to find that the two are different.

isNaN(undefined)    // true
Number.isNaN(undefined)  //false
Copy the code

I looked up related questions to figure out what the difference was. The interpretation of global isNaN on MDN is as follows:

The global NaN property is a value representing Not-A-Number.

That is, global isNaN simply checks if a value is not a number. IsNaN’s full name is “Is Not a Number,” and its function can be understood literally.

However, if you want to determine whether a value is strictly equal to a NaN, global isNaN seems to be unable to do this, because any value passed in that cannot be converted to a number is returned as true. The global isNaN type converts the incoming value to a numeric font and then determines if ==NaN.

isNaN(NaN)  //true
isNaN('123')   //false can be converted to number
isNaN(true)    //false can be converted to number
isNaN('this is a str')   //true, the conversion to a number is NaN
isNaN(undefined)   //true, undefined converts to NaN
Copy the code

Obviously a string is not a number, nor is it a NaN. To correct this bug, ES6 provides number. isNaN to determine whether a value is strictly equal to NaN.

isNaN(NaN)  //true
Number.isNaN(NaN)  //true

isNaN('this is a str')   // true
Number.isNaN('this is a str')   //false
isNaN(undefined)   // true
Number.isNaN(undefined)   //false
Copy the code

NaN! ==NaN

parseInt(5/'d') = = =Number('ddd')    // false
NaN= = =NaN  // false
Copy the code

NaN is just a static property on Number, and one can be obtained by number.nan. The Number(‘ DDD ‘) operation gives you NaN, which is just to tell you that the value is not a Number, a representation, but not an exact valid value, so NaN cannot participate in the calculation or be compared to itself. So it can also be said that NaN has properties that are not equal to itself.

How do I determine that two Nans are equal

In ES5, the object.is () method is provided to determine whether two values belong to the same value, and this method can be used to determine whether NaN are equal, for example

Object.is(NaN.NaN);  // true
Copy the code

In the ES6Number.isNaNThe polyfill

if (!Number.isNaN) {
  Number.isNaN = function(n) {
    return (
      typeof n === 'number' && window.isNaN(n)
    );
  };
}
Copy the code

Another polyfill that uses NaN is not equal to its own property:

if (!Number.isNaN) {
    Number.isNaN = function(n) {
        returnn ! == n; }; }Copy the code

Reference:

www.cnblogs.com/echolun/p/1…

Segmentfault.com/a/119000001…