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

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

当前回答

ECMA-262 6.0 (ES6)标准包括编号。isInteger函数。

为了增加对旧浏览器的支持,我强烈建议使用强大的和社区支持的解决方案:

https://github.com/paulmillr/es6-shim

这是一个纯粹的ES6 JS polyfills库。

注意,这个库需要es5-shim,只需遵循README.md即可。

其他回答

你可以检查这个数字是否有余数:

var data = 22;

if(data % 1 === 0){
   // yes it's an integer.
}

请注意,如果你的输入也可以是文本,你想先检查它不是,那么你可以先检查类型:

var data = 22;

if(typeof data === 'number'){
     // yes it is numeric

    if(data % 1 === 0){
       // yes it's an integer.
    }
}

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

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

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

Lodash https://lodash.com/docs#isInteger(自4.0.0起)有函数检查变量是否为整数:

_.isInteger(3);
// → true

_.isInteger(Number.MIN_VALUE);
// → false

_.isInteger(Infinity);
// → false

_.isInteger('3');
// → false

ECMA-262 6.0 (ES6)标准包括编号。isInteger函数。

为了增加对旧浏览器的支持,我强烈建议使用强大的和社区支持的解决方案:

https://github.com/paulmillr/es6-shim

这是一个纯粹的ES6 JS polyfills库。

注意,这个库需要es5-shim,只需遵循README.md即可。

var x = 1.5;
if(!isNaN(x)){
 console.log('Number');
 if(x % 1 == 0){
   console.log('Integer');
 }
}else {
 console.log('not a number');
}