确定 JavaScript 值是否为“整数”

Determine if JavaScript value is an "integer"?

本文关键字:整数 是否 JavaScript 确定      更新时间:2023-09-26

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

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

例:

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

我使用以下方法从 URL 获取 ID。

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

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

试试这个:

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

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

下面是Number谓词函数的填充代码:

"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 ,它不在规范中,因为我编造了它。因此,您可以减小此填充代码的大小:

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

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

使用 jQuery 的 IsNumeric 方法。

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

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

更正:这不会确保整数。 这将:

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

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