An article to talk about NaN in JavaScript

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

An article to talk about NaN in JavaScript

In JavaScript,NaNis a special numeric value (the result oftypeof NaNisnumber), which isnot a numberis 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 isNaN
NaN + 1 // NaN 10 / NaN // NaN
Copy after login

2. Notes

NaNisthe only value thatis not equal to itself:

NaN === NaN // false
Copy after login

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

Why isisNaN()not used to determine whether it is the valueNaN? BecauseisNaNdoesn'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
Copy after login

So we want to make sure that this value isNaN, we can use the following two methods:

  • Method 1: ChangeisNaN()is combined withtypeofto determine
function isValueNaN(value) { return typeof value === 'number' && isNaN(value) }
Copy after login
  • Method 2: Whether the value is not equal to itself (NaNisOnlyThe 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!