In JavaScript,NaN
is a special numeric value (the result oftypeof NaN
isnumber
), which isnot 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
isthe only value thatis not equal to itself:
NaN === NaN // false
3. How To identify NaN
we can use the global functionisNaN()
to determine whether a value is anon-number(not used to determine whether Not the valueNaN
):
isNaN(NaN) // true isNaN(10) // false
Why isisNaN()
not used to determine whether it is the valueNaN
? BecauseisNaN
doesn't work on non-numbers, the first thing it does is convert these values to numbers, which may result inNaN
, and then the function will incorrectly returntrue
:
isNaN('abc') // true
So we want to make sure that this value isNaN
, we can use the following two methods:
isNaN()
is combined withtypeof
to determinefunction isValueNaN(value) { return typeof value === 'number' && isNaN(value) }
NaN
isOnlyThe 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!