Home >Web Front-end >JS Tutorial >How to determine whether it is a numeric type in javascript
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.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
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
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) }
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]
function isNumber(num) { return Object.prototype.toString.call(num) === '[object Number]' && !isNaN(num) }
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!