81

可能重复:
检查变量是否包含 Javascript 中的数值?

如何检查变量是否是 jQuery 中的整数?

例子:

if (id == int) { // Do this }

我使用以下内容从 URL 获取 ID。

var id = $.getURLParam("id");

但我想检查变量是否为整数。

4

3 回答 3

198

试试这个:

if(Math.floor(id) == id && $.isNumeric(id)) 
  alert('yes its an int!');

$.isNumeric(id)检查它是否是数字
Math.floor(id) == id然后确定它是否真的是整数值而不是浮点数。如果它是浮点数,则将其解析为 int 将给出与原始值不同的结果。如果它是 int 两者将是相同的。

于 2012-04-22T18:12:09.943 回答
49

这是Number谓词函数的polyfill:

"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

所有主流浏览器都支持这些功能,除了isNumeric,因为我编的所以不在规范中。因此,您可以减小此 polyfill 的大小:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

n === +n或者,只需手动内联表达式。

于 2012-04-22T18:29:38.317 回答
29

使用 jQuery 的 IsNumeric 方法。

http://api.jquery.com/jQuery.isNumeric/

if ($.isNumeric(id)) {
   //it's numeric
}

更正:这不能确保整数。这个会:

if ( (id+"").match(/^\d+$/) ) {
   //it's all digits
}

当然,这不使用 jQuery,但我认为只要解决方案有效,jQuery 实际上并不是强制性的

于 2012-04-22T18:12:17.570 回答