Home  >  Article  >  Web Front-end  >  How to determine whether it is a numeric type in javascript

How to determine whether it is a numeric type in javascript

青灯夜游
青灯夜游Original
2021-04-12 18:32:296942browse

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)
}

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)
}

[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)
}

Fourth: Regular expression (the most recommended one)

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

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!

Statement:
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