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

How to determine whether it is a numeric type in javascript

青灯夜游
Release: 2023-01-05 16:07:45
Original
6964 people have browsed it

Method: 1. Use the typeof keyword and isNaN() function to judge; 2. Use the typeof keyword and isFinite() function to judge; 3. Use "Object.prototype.toString.call" to judge; 4. Use regular expressions to determine.

How to determine whether it is a numeric type in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

js summary of judging numeric types

When I was writing code recently, some logic needed to judge the numeric type. When I used it, I realized that the method I understood was not very strict, and then I decided to check it out. Summary of data to understand which methods are more rigorous

The first one: typeof isNaN

Use typeof to determine whether it is a numeric type, but NaN is also a numeric type. In order To eliminate this possibility, further filter out by isNaN. This method will miss Infinity

function isNumber(num) {
	return typeof num === 'number' && !isNaN(num)
}
Copy after login

The second type: typeof isFinite

Use typeof to determine whether it is a numeric type, but NaN and Infinity are also numeric types. In order To eliminate this possibility, further filter out NaN and Infinity through isFinite

function isNumber(num) {
	return typeof num === 'number' && isFinite(num)
}
Copy after login

[Recommended learning: javascript Advanced Tutorial]

The third type: Object. prototype.toString.call

function isNumber(num) {
	return Object.prototype.toString.call(num) === '[object Number]'  && !isNaN(num)
}
Copy after login

Fourth: Regular expression (the most recommended one)

function isNumber(num) {
	return /^[0-9]+.?[0-9]*$/.test(num)
}
Copy after login

For more programming-related knowledge, please visit : Programming Video! !

The above is the detailed content of How to determine whether it is a numeric type in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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