Home >Web Front-end >JS Tutorial >An article to talk about NaN in JavaScript

An article to talk about NaN in JavaScript

青灯夜游
青灯夜游forward
2022-10-24 09:19:441838browse

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:

  • A number that cannot be parsed
Number('abc') // NaN
Number(undefined) // NaN
  • Failed operation
Math.log(-1) // NaN
Math.sqrt(-1) // NaN
Math.acos(2)  // NaN
  • An operator is 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:

  • Method 1: Change isNaN() is combined with typeof to determine
function isValueNaN(value) {
	return typeof value === 'number' && isNaN(value)
}
  • Method 2: Whether the value is not equal to itself (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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete