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

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

当前回答

为什么没有人提到Number.isInteger() ?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

为我完美地工作,并解决了NaN开始一个数字的问题。

其他回答

使用|运算符:

(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
var x = 1.5;
if(!isNaN(x)){
 console.log('Number');
 if(x % 1 == 0){
   console.log('Integer');
 }
}else {
 console.log('not a number');
}

答案中有很多选项。

isNaN对于纯整数来说可能很棘手,您仍然需要其他检查来使它过时。 Number.isInteger()在IE中不受官方支持(大多数人不会关心,但也有一些掉队者)。

最后我自己写了一些东西:

function isInteger(valueToCheck) {
    return typeof valueToCheck !== 'undefined'
        && (valueToCheck === parseInt(valueToCheck, 10));
}

Test

let undefinedValue;
const testValues = [
    1,
    '',
    undefinedValue,
    1.1,
    '1',
    '1.1',
    '1-2',
    'bob',
    false,
    [],
    [1],
    {},
    {foo: 1}
];

testValues.forEach(value => {
    console.log(`${value} - ${isInteger(value)}`);
})

结果:

1 - true
'' - false
undefined - false
1.1 - false
'1' - false
'1.1' - false
'1-2' - false
'bob' - false
false - false
[] - false
[1] - false
{} - false
{foo: 1} - false

一些测试值是多余的,但它们的存在只是清楚地表明没有任何东西通过。你可以省略函数中的未定义检查,但我发现在JS中未定义的东西可能会很奇怪,所以感觉更安全。

我的方法:

a >= 1e+21→只适用于非常大的数字。这将肯定涵盖所有情况,不像本讨论中提供的其他解决方案。

A === (A |0)→如果给定函数的实参与按位转换的值完全相同(===),则意味着实参是一个整数。

A |0→对于A的任何非数字值都返回0,如果A确实是数字,它将去掉小数点后的所有数字,因此1.0001将变成1

const isInteger = n => n >= 1e+21 ? true : n === (n|0); // tests: [ [1, true], [1000000000000000000000, true], [4e2, true], [Infinity, true], [1.0, true], [1.0000000000001, false], [0.1, false], ["0", false], ["1", false], ["1.1", false], [NaN, false], [[], false], [{}, false], [true, false], [false, false], [null, false], [undefined, false], ].forEach(([test, expected]) => console.log( isInteger(test) === expected, typeof test, test ) )