JavaScript,NaNIs a special numeric value (typeof NaNAs the result of thenumber), it isnot a numberIs not a valid number.

1. Generation of NaN:

  • A number that cannot be parsed
Number('abc') // NaN
Number(undefined) // NaN
Copy the code
  • Failed operation
Math.log(-1) // NaN
Math.sqrt(-1) // NaN
Math.acos(2)  // NaN
Copy the code
  • One operator isNaN
NaN + 1 // NaN
10 / NaN  // NaN
Copy the code

2. Pay attention to the point

NaNisThe only one2. A value not equal to itself:

NaN= = =NaN  // false
Copy the code

3. How do YOU identify nans

We can use global functionsisNaN()To determine whether a number is a numberThe digital(Not to determine whether or notNaNThis value) :

isNaN(NaN)  // true
isNaN(10)  // false
Copy the code

Why do you sayisNaN()It’s not about whether or notNaNWhat about this value? becauseisNaNIt doesn’t work for non-numbers, so the first thing it does is convert these values to numbers, and the result of that conversion might be zeroNaN, and then the function returns in errortrue:

isNaN('abc')  // true
Copy the code

So we want to make sure that one of these values is zeroNaN, the following two methods can be used:

  • Method 1: willisNaN()andtypeofJudge by combination
function isValueNaN(value) {
    return typeof value === 'number' && isNaN(value)
}
Copy the code
  • Method 2: Is the value not equal to itself (NaNisThe onlyA value having such a characteristic.
function isValueNaN(value) {
    returnvalue ! == value }Copy the code