Home > Article > Web Front-end > An article to talk about NaN in JavaScript
In JavaScript, NaN
is a special numeric value (the result of typeof NaN
is number
), which is not a number
is an abbreviation, indicating that it is not a legal number.
1. Generation of NaN:
Number('abc') // NaN Number(undefined) // NaN
Math.log(-1) // NaN Math.sqrt(-1) // NaN Math.acos(2) // NaN
NaN
NaN + 1 // NaN 10 / NaN // NaN
2. Notes
NaN
is the only value that is not equal to itself:
NaN === NaN // false
3. How To identify NaN
we can use the global function isNaN()
to determine whether a value is a non-number (not used to determine whether Not the value NaN
):
isNaN(NaN) // true isNaN(10) // false
Why is isNaN()
not used to determine whether it is the value NaN
? Because isNaN
doesn't work on non-numbers, the first thing it does is convert these values to numbers, which may result in NaN
, and then the function will incorrectly return true
:
isNaN('abc') // true
So we want to make sure that this value is NaN
, we can use the following two methods:
isNaN()
is combined with typeof
to determine function isValueNaN(value) { return typeof value === 'number' && isNaN(value) }
NaN
is OnlyThe value with such characteristics)function isValueNaN(value) { return value !== value }
[Related recommendations: javascript video tutorial, Programming video】
The above is the detailed content of An article to talk about NaN in JavaScript. For more information, please follow other related articles on the PHP Chinese website!