Detailed explanation of isNaN() and the difference between isNaN() and Number.isNaN()

isNaN usage:

Let's first look at a set of results:
Insert picture description here
among them, true and false can be converted into numbers 1 and 0 by Number,
null and empty arrays [] can be converted into numbers by Number 0
objects {} and undefined cannot be converted into numbers by Number, return NaN
can be converted to a numeric value by Number for an empty string or a space string or a number string.
For an array:
Insert picture description here
So we probably know which values ​​can be converted to numbers by Number and which cannot, which can be simply understood as:

For the value x that can be converted to a numeric value by Number, then isNaN(x) is false.
If the value y cannot be converted to a numeric value by Number, then isNaN(y) is true

Insert picture description here
For a special object such as Date():
Insert picture description here
new Date() can be converted to a number by Number, so isNaN(new Date()) === false
Insert picture description here
it new Date().toString()returns a formatted string, which cannot be converted to a number by Number, soisNaN(new Date().toString()) === true
Insert picture description here
note:Insert picture description here
Insert picture description here
Insert picture description here

The difference between isNaN() and Number.isNaN()

When we pass a parameter to isNaN, its original intention is to try to convert the parameter to the Number type through the Number() method. If it succeeds, it returns false, and if it fails, it returns true.
So isNaN only judges whether the passed parameter can be converted into a number, not strictly judge whether it is equal to NaN

Number('测试') // 输出NaN
// 因为没有将“测试”成功转换成Number类型,所以下面代码输出true
console.log(isNaN('测试')) //  true

Number.isNaN judges whether the passed parameter is strictly equal to NaN (that is, ===).

Under what circumstances will Number.isNaN be used?

When performing operations on two variables, we can use Number.isNaN to determine whether its value is NaN:

console.log(Number.isNaN(2/'测试')); //  输出true

The most difference between Number.isNaN and isNaN is that Number.isNaN does not have type conversion behavior.

console.log(isNaN('测试')) //true
console.log(Number.isNaN('测试')) //false

In the above code, the string "test" is passed in, but why is the result different? the reason is:

isNaN will use the Number method to try to convert the string "test" to the Number type, but the conversion fails. Because the result of Number('test') is NaN, it finally returns true.

The Number.isNaN method only strictly judges whether the incoming parameters are all equal to NaN ('test' === NaN). Of course, the string is not all equal to NaN, so it outputs false.

Guess you like

Origin blog.csdn.net/dyw3390199/article/details/114522813