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

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

当前回答

试试下面的功能:

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

其他回答

从http://www.toptal.com/javascript/interview-questions:

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

我发现这是最好的方法。

我必须检查一个变量(字符串或数字)是否为整数,我使用了这个条件:

function isInt(a){
    return !isNaN(a) && parseInt(a) == parseFloat(a);
}

http://jsfiddle.net/e267369d/1/

其他一些答案也有类似的解决方案(依赖于parseFloat与isNaN相结合),但我的答案应该更直接和自我解释。


编辑:我发现我的方法失败的字符串包含逗号(如“1,2”),我也意识到,在我的特定情况下,我希望函数失败,如果字符串不是一个有效的整数(应该失败的任何浮点数,甚至1.0)。这是我的函数Mk II

function isInt(a){
    return !isNaN(a) && parseInt(a) == parseFloat(a) && (typeof a != 'string' || (a.indexOf('.') == -1 && a.indexOf(',') == -1));
}

http://jsfiddle.net/e267369d/3/

当然,如果你真的需要这个函数接受整数浮点数(1.0之类的东西),你总是可以删除点条件a.indexOf('.') == -1。

试试这个:

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

答案中有很多选项。

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中未定义的东西可能会很奇怪,所以感觉更安全。

你可以使用这个函数:

function isInteger(value) {
    return (value == parseInt(value));
}

即使值是包含整数值的字符串,它也将返回true。 因此,结果将是:

alert(isInteger(1)); // true
alert(isInteger(1.2)); // false
alert(isInteger("1")); // true
alert(isInteger("1.2")); // false
alert(isInteger("abc")); // false