How does JavaScript tell if a variable is a numeric type?

Source: Internet
Author: User
IsNaN () cannot determine if a variable is a numeric type, and the value of IsNaN (123) is False,isnan (' 123 ') and false.
The actual function of IsNaN () is not consistent with its name IsNaN, IsNaN (NaN) value is True,isnan (number ("XYZ")) value is True,isnan ("abc") value is True,isnan (123/0) value is false, So it actually evaluates to true for other types that cannot be converted to number type and to their own Nan, and all number types except their own Nan are judged to be false (the type of Nan is also number). Other types that can be converted to number types are also judged to be false, such as the ' 123 ' type is string but is judged to be false.
typeof (num) = = "Number" is more accurate, but Nan is also number type, number ("XYZ") is also the number type, if you just distinguish between 123 and ' 123 ', then there is no problem, you can use typeof (num) = = = " Number ". If you want to exclude a divisor of 0, then judge (num!==infinity), i.e. (typeof (num) = = "Number") && (num!==infinity).
A bit more comprehensive: (typeof (num) = = = "Number") && (num!==infinity) &&!isnan (num)

Number.isnan () has been added to ECMAScript 6 and Firefox has been implemented.
The code is as follows:


Nan is the only value that satisfies the (x!== x) inequality

How does JavaScript tell if a variable is a numeric type?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.