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

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

当前回答

这将解决另一个场景(121.),结束处有一个点

function isInt(value) {
        var ind = value.indexOf(".");
        if (ind > -1) { return false; }

        if (isNaN(value)) {
            return false;
        }

        var x = parseFloat(value);
        return (x | 0) === 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
}
if(Number.isInteger(Number(data))){
    //-----
}

首先,NaN是一个“数字”(是的,我知道这很奇怪,就这样吧),而不是一个“函数”。

你需要检查变量的类型是否为数字,如果是整数,我会使用模数。

alert(typeof data === 'number' && data%1 == 0);

你可以使用一个简单的正则表达式:

function isInt(value) {
    var er = /^-?[0-9]+$/;
    return er.test(value);
}

使用===运算符(严格相等),如下所示:

if (data === parseInt(data, 10))
    alert("data is integer")
else
    alert("data is not an integer")