Kai*_*all 76 javascript jquery
可能重复:
检查变量是否包含Javascript中的数值?
如何在jQuery中检查变量是否为整数?
例:
if (id == int) { // Do this }
Run Code Online (Sandbox Code Playgroud)
我使用以下内容从URL获取ID.
var id = $.getURLParam("id");
Run Code Online (Sandbox Code Playgroud)
但我想检查变量是否是整数.
bar*_*iir 181
试试这个:
if(Math.floor(id) == id && $.isNumeric(id))
alert('yes its an int!');
Run Code Online (Sandbox Code Playgroud)
$.isNumeric(id)检查它是否为数字
Math.floor(id) == id然后将确定它是否真的是整数值而不是浮点数.如果它是一个浮点解析它到int将给出与原始值不同的结果.如果是int则两者都是相同的.
Aad*_*hah 49
@bardiir使用类似的方法来检查值是否为数字.然而,这种方法更简单.
"use strict";
Number.isNaN = Number.isNaN ||
n => n !== n; // only NaN
Number.isNumeric = Number.isNumeric ||
n => n === +n; // all numbers excluding NaN
Number.isFinite = Number.isFinite ||
n => n === +n // all numbers excluding NaN
&& n >= Number.MIN_VALUE // and -Infinity
&& n <= Number.MAX_VALUE; // and +Infinity
Number.isInteger = Number.isInteger ||
n => n === +n // all numbers excluding NaN
&& n >= Number.MIN_VALUE // and -Infinity
&& n <= Number.MAX_VALUE // and +Infinity
&& !(n % 1); // and non-whole numbers
Number.isSafeInteger = Number.isSafeInteger ||
n => n === +n // all numbers excluding NaN
&& n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
&& n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
&& !(n % 1); // and non-whole numbers
Run Code Online (Sandbox Code Playgroud)
Number强迫isNumeric一个数字.然后我们使用strict equality(n === +n)来检查它是否是整数.简单高效.
编辑:似乎很多人需要检查数字类型,所以我将共享一个我经常用于此目的的函数列表:
"use strict";
Number.isNumeric = Number.isNumeric ||
n => n === +n; // all numbers excluding NaN
Run Code Online (Sandbox Code Playgroud)
希望这对某人有用.
Mar*_*arc 26
使用jQuery的IsNumeric方法.
http://api.jquery.com/jQuery.isNumeric/
if ($.isNumeric(id)) {
//it's numeric
}
Run Code Online (Sandbox Code Playgroud)
更正:这不会确保整数.这个会:
if ( (id+"").match(/^\d+$/) ) {
//it's all digits
}
Run Code Online (Sandbox Code Playgroud)
当然,这不使用jQuery,但我认为只要解决方案有效,jQuery实际上并不是强制性的