我如何检查如果一个变量是一个整数在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 isInteger = /^[0-9]\d*$/;

isInteger.test(123); //true
isInteger.test('123'); // true
isInteger.test('sdf'); //false
isInteger.test('123sdf'); //false

// If u want to avoid string value:
typeof testVal !== 'string' && isInteger.test(testValue);

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

为文本框添加类numOnly,

$(document).on("input", ".numOnly", function(e) {
    this.value = this.value.replace(/[^0-9\$]/g,'');
    if(this.value!=""){
      alert('Integer Number.');
    }else{
      alert('Not an Integer Number.');
   }
});

这对我有用。试试这个

你可以使用键盘,键上,键下等,而不是输入。

function isInteger(argument) { return argument == ~~argument; }

用法:

isInteger(1);     // true<br>
isInteger(0.1);   // false<br>
isInteger("1");   // true<br>
isInteger("0.1"); // false<br>

or:

function isInteger(argument) { return argument == argument + 0 && argument == ~~argument; }

用法:

isInteger(1);     // true<br>
isInteger(0.1);   // false<br>
isInteger("1");   // false<br>
isInteger("0.1"); // false<br>

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

_.isInteger(3);
// → true

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

_.isInteger(Infinity);
// → false

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