判断方法:1、使用“$.isnumeric(x)”,可判断指定参数“x”是否是数字值;2、使用“isnan(x)”,可判断参数“x”是否是为数字值;3、使用正则表达式“/^(-)?\d+(\.\d+)?$/”配合test来判断数字。
本教程操作环境:windows7系统、jquery3.2.1版,该方法适用于所有品牌电脑。
相关推荐:《jquery视频》
jquery判断变量是否为数字的方法
方法1、使用$.isnumeric()
jquery里内置的一个用来判断是否为数字的函数$.isnumeric()。$.isnumeric() 函数用于判断指定参数是否是一个数字值。
用$.isnumeric()来判断是否为数字的话,一些特殊的字符会被当成8进制或12进制的数字,判定为true。
注意:在jquery 3.0中,$.isnumeric()方法只有接收number类型的参数,或者是可以被强制为有限数值的 string类型的参数时,才会返回true,否则返回false。
语法
$.isnumeric( value )
参数:
value:任意类型,需要进行判断的任意值。
示例:
$.isnumeric(3.13); //true$.isnumeric("3.13"); //true$.isnumeric(-3.13); //true$.isnumeric("-3.13"); //true$.isnumeric("03.13"); //true$.isnumeric(01); //true$.isnumeric(001); //true$.isnumeric(+3.13); //true$.isnumeric(0xff); //true$.isnumeric("0xff"); //true$.isnumeric(true); //false$.isnumeric(nan); //false
方法2:使用isnan() 函数
var val = $("#test").val();var ival = parseint(val);//如果变量val是字符类型的数则转换为int类型 如果不是则ival为nan alert(typeof(ival)); if(!isnan(ival)){ alert(val +"是数字"); } else{ alert(val +"不是数字"); }
说明: isnan()函数,如果传入的参数是数字返回false,否则返回true
方法3:使用正则表达式判断
常用正则:
" /^(0|[1-9]\d*)$/" //非负整数(正整数 + 0) "^[0-9]*[1-9][0-9]*$" //正整数 "^((-\\d+)|(0+))$" //非正整数(负整数 + 0) "^-[0-9]*[1-9][0-9]*$" //负整数 "^-?\\d+$" //整数 "^\\d+(" //非负浮点数(正浮点数 + 0) "^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$"//正浮点数 "^((-\\d+(" //非正浮点数(负浮点数 + 0) "^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$" //负浮点数 "^(-?\\d+)(" //浮点数
实例:
var r = /^\+?[1-9][0-9]*$/;//判断是否为正整数 r.test(str);
或者:
function isnumber(value) { //验证是否为数字 var patrn = /^(-)?\d+(\.\d+)?$/; if (patrn.exec(value) == null || value == "") { return false } else { return true }}
知识拓展:javascript的number()函数 —-这里不是判断方法
<script type="text/javascript"> var test1= new boolean(true);var test2= new boolean(false);var test3= new date();var test4= new string("999");var test5= new string("999 888"); document.write(number(test1)+ "<br />");document.write(number(test2)+ "<br />");document.write(number(test3)+ "<br />");document.write(number(test4)+ "<br />");document.write(number(test5)+ "<br />");</script>
输出的结果是:
1 0 1492855437972 999 nan
可以看出在javascript中0代表false,1代表true。但是我测试了一下,除0以外的数放在if的条件中,都可以执行if语句内容。所以。可以得出除0以外的所有数都可以代表true。
更多编程相关知识,请访问:编程课程!!
以上就是jquery如何判断是否为数字?的详细内容。