我如何检查如果一个变量是一个整数在JavaScript,并抛出一个警告,如果它不是?我试过了,但不管用:

<html>
    <head>
        <script type="text/javascript">
            var data = 22;
            alert(NaN(data));
        </script>
    </head>
</html>

当前回答

使用|运算符:

(5.3 | 0) === 5.3 // => false
(5.0 | 0) === 5.0 // => true

所以,一个测试函数可能是这样的:

var isInteger = function (value) {
  if (typeof value !== 'number') {
    return false;
  }

  if ((value | 0) !== value) {
    return false;
  }

  return true;
};

其他回答

ecmascript -6之前最简单、最清晰的解决方案(它也足够健壮,即使传递给函数的是一个非数字值,如字符串或null,也会返回false)如下:

function isInteger(x) { return (x^0) === x; } 

下面的解决方案也可以工作,尽管没有上面的那样优雅:

function isInteger(x) { return Math.round(x) === x; }

注意,在上述实现中Math.ceil()或Math.floor()也可以同样好地使用(而不是Math.round())。

或者:

function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }

一个相当常见的错误解决方案是:

function isInteger(x) { return parseInt(x, 10) === x; }

While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:

> String(1000000000000000000000)
'1e+21'

> parseInt(1000000000000000000000, 10)
1

> parseInt(1000000000000000000000, 10) === 1000000000000000000000
false

这要看情况,你是否也想将字符串转换为潜在整数?

这样做:

function isInt(value) {
  return !isNaN(value) && 
         parseInt(Number(value)) == value && 
         !isNaN(parseInt(value, 10));
}

按位操作

简单的解析和检查

function isInt(value) {
  var x = parseFloat(value);
  return !isNaN(value) && (x | 0) === x;
}

短路并保存解析操作:

function isInt(value) {
  if (isNaN(value)) {
    return false;
  }
  var x = parseFloat(value);
  return (x | 0) === x;
}

或者两者同时出现:

function isInt(value) {
  return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
}

测试:

isInt(42)        // true
isInt("42")      // true
isInt(4e2)       // true
isInt("4e2")     // true
isInt(" 1 ")     // true
isInt("")        // false
isInt("  ")      // false
isInt(42.1)      // false
isInt("1a")      // false
isInt("4e2a")    // false
isInt(null)      // false
isInt(undefined) // false
isInt(NaN)       // false

这是小提琴:http://jsfiddle.net/opfyrqwp/28/

性能

测试表明,短路解决方案具有最佳的性能(ops/sec)。

// Short-circuiting, and saving a parse operation
function isInt(value) {
  var x;
  if (isNaN(value)) {
    return false;
  }
  x = parseFloat(value);
  return (x | 0) === x;
}

下面是一个基准: http://jsben.ch/#/htLVw

如果你喜欢更短的钝角短路形式:

function isInt(value) {
  var x;
  return isNaN(value) ? !1 : (x = parseFloat(value), (0 | x) === x);
}

当然了,我建议让这个小工具来处理。

假设你对问题中的变量一无所知,你应该采用这种方法:

if(typeof data === 'number') {
    var remainder = (data % 1);
    if(remainder === 0) {
        // yes, it is an integer
    }
    else if(isNaN(remainder)) {
        // no, data is either: NaN, Infinity, or -Infinity
    }
    else {
        // no, it is a float (still a number though)
    }
}
else {
    // no way, it is not even a number
}

简单来说:

if(typeof data==='number' && (data%1)===0) {
    // data is an integer
}

在今天的浏览器中,Number.isInteger()是一种方式,就像之前解释的许多答案一样,但我遇到了一个常见的问题,它发生在我构建API的时候。

所以在API请求中,我们以字符串的形式接收属性,因此Number.isInteger()将返回false。

如果我们尝试用Number.isInteger(parseInt())检查它,那么值就像1.1或1。Asd返回true

为了解决这个问题,我创建了一个函数,它检查值是否为整数,将其作为整数或字符串传递

function isNumber(value) {
    return ([...value.toString()]
            .filter(x => [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' ]
            .indexOf(x) >= 0))
            .length == Math.max(value.toString().length, 1)
}

Math.max()部分用于处理空字符串

试试这个:

let number = 5;
if (Number.isInteger(number)) {
    //do something
}