Home > Web Front-end > JS Tutorial > body text

An article to talk about NaN in JavaScript

青灯夜游
Release: 2022-10-24 09:19:44
forward
1782 people have browsed it

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
Copy after login
  • Failed operation
Math.log(-1) // NaN
Math.sqrt(-1) // NaN
Math.acos(2)  // NaN
Copy after login
  • An operator is NaN
NaN + 1 // NaN
10 / NaN  // NaN
Copy after login

2. Notes

NaN is the only value that is not equal to itself:

NaN === NaN  // false
Copy after login

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
Copy after login

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
Copy after login

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)
}
Copy after login
  • Method 2: Whether the value is not equal to itself (NaN is OnlyThe value with such characteristics)
function isValueNaN(value) {
	return value !== value
}
Copy after login

[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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template