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

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

当前回答

在今天的浏览器中,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()部分用于处理空字符串

其他回答

Number.isInteger()似乎是可行的方法。

MDN还为不支持Number.isInteger()的浏览器提供了以下填充,主要是所有版本的IE。

链接到MDN页面

Number.isInteger = Number.isInteger || function(value) {
    return typeof value === "number" && 
           isFinite(value) && 
           Math.floor(value) === value;
};

试试下面的功能:

function isInteger (num) {
    return num == parseInt(+num,10)  && !isNaN(parseInt(num));
}

console.log ( isInteger(42));        // true
console.log ( isInteger("42"));      // true
console.log ( isInteger(4e2));       // true
console.log ( isInteger("4e2"));     // true
console.log ( isInteger(" 1 "));     // true
console.log ( isInteger(""));        // false
console.log ( isInteger("  "));      // false
console.log ( isInteger(42.1));      // false
console.log ( isInteger("1a"));      // false
console.log ( isInteger("4e2a"));    // false
console.log ( isInteger(null));      // false
console.log ( isInteger(undefined)); // false
console.log ( isInteger(NaN));       // false    
console.log ( isInteger(false));       // false
console.log ( isInteger(true));       // false
console.log ( isInteger(Infinity));       // false

检查变量是否等于相同的变量四舍五入为整数,就像这样:

if(Math.round(data) != data) {
    alert("Variable is not an integer!");
}

在经历了几次成功和失败之后,我想出了这个解决方案:

const isInt = (value) => {
  return String(parseInt(value, 10)) === String(value)
}

我喜欢上面的想法,检查不是NaN的值并使用parseFloat,但当我在React基础设施中尝试它时,由于某些原因它不起作用。

编辑: 我找到了一个不用字符串的更好的方法:

var isInt = function (str) {
  return str === '0' || !!~~str;
}

我认为这是最简短的答案。也许是最有效的,但我可以更正一下。:)

在今天的浏览器中,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()部分用于处理空字符串