JavaScript judges whether a string is a number type: Number.isInteger, isNaN, regular expression comparison

Preface : The front end often needs to deal with some numerical problems, involving the judgment of integers or decimals.
Here are a few simple ways to judge:

Method 1: JavaScript isInteger() method

The isInteger() method determines whether the incoming value is an integer.
Returns true if the passed argument is an integer, false otherwise, or false
if the passed argument is NaN or infinite.
grammar:

Number.isInteger(value)   //value要测试的值是整数
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(20);// true
Number.isInteger(25);// true
Number.isInteger(-100000);   // true
Number.isInteger(0.1);   // false
Number.isInteger(3.14);  // false
Number.isInteger(NaN);   // false
Number.isInteger(Infinity);  // false
Number.isInteger('10');  // false
Number.isInteger(true);  // false
Number.isInteger(false); // false

insert image description here

Method 2: Regular Expressions

It is safer to use regular expressions, but the disadvantage is that the performance is slightly worse.

function isNumber(val){
    
    
	 return /^[-]?[\.\d]+$/.test(val);
}

Method 3: Number type conversion

The idea is to convert it into a number first, and then see if it is NaN

function isNumber(val){
    
    
	return !isNaN(Number(val))
}

Method 4: Use isNaN directly

According to the method 3 variant, in fact, you can use isNaN directly without performing type conversion:

function isNumber(val){
    
    
	return !isNaN(val);
}
Reference blog:

JavaScript isInteger() method https://www.nhooo.com/jsref/number_isinteger.html#top

JavaScript judges whether a string is a number type: Number.isInteger, isNaN, regular expression comparison
http://ourjs.com/detail/k96ccn5eixcg

Guess you like

Origin blog.csdn.net/qq_26780317/article/details/126783596