Home > Article > Web Front-end > How to determine whether a specified value is a number in javascript
Judgment method: 1. Use the isNaN() function, the syntax "isNaN(value)", if the value is a number, return false; 2. Use the return value of typeof, the syntax "typeof(value)", if If the returned value is "Number", it is a number; 3. Use regular expressions to judge.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript determines whether the specified value is a number
Method 1: isNaN() function
The isNaN() function determines whether a value is Not-a-Number. This function returns true if the value is equal to NaN. Otherwise return false.
var c="hello"; //字符串 isNaN(c); //返回一个true; var c=10; //数字 isNaN(c);//返回一个false
The disadvantage of isNaN() is that null, space and empty string will be processed as 0, which needs to be optimized
/** *判断是否是数字 * **/ function isRealNum(val){ // isNaN()函数 把空串 空格 以及NUll 按照0来处理 所以先去除, if(val === "" || val ==null){ return false; } if(!isNaN(val)){ //对于空数组和只有一个数值成员的数组或全是数字组成的字符串, //isNaN返回false,例如:'123'、[]、[2]、['123'],isNaN返回false, //所以如果不需要val包含这些特殊情况,则这个判断改写为if(!isNaN(val) && typeof val === 'number' ) return true; } else{ return false; } }
Method 2: Use the return value of typeof
Verification method: If the returned value is Number, it is a number; if the return value is String or other, it is not a number. As shown below:
var a=123; var b='123abc'; typeof(a) //Number typeof(b) //String
Method 3: Use regular expressions
(1), check as long as it is a number (including positive and negative integers, 0 and positive and negative floats Points) will return true
/** * 校验只要是数字(包含正负整数,0以及正负浮点数)就返回true **/ function isNumber(val){ var regPos = /^\d+(\.\d+)?$/; //非负浮点数 var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数 if(regPos.test(val) && regNeg.test(val)){ return true; }else{ return false; } }
(2), if the positive and negative numbers are verified, true will be returned
/** * 校验正负正数就返回true **/ function isIntNum(val){ var regPos = / ^\d+$/; // 非负整数 var regNeg = /^\-[1-9][0-9]*$/; // 负整数 if(regPos.test(val) && regNeg.test(val)){ return true; }else{ return false; } }
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to determine whether a specified value is a number in javascript. For more information, please follow other related articles on the PHP Chinese website!