我如何检查如果一个变量是一个整数在JavaScript,并抛出一个警告,如果它不是?我试过了,但不管用:
<html>
<head>
<script type="text/javascript">
var data = 22;
alert(NaN(data));
</script>
</head>
</html>
我如何检查如果一个变量是一个整数在JavaScript,并抛出一个警告,如果它不是?我试过了,但不管用:
<html>
<head>
<script type="text/javascript">
var data = 22;
alert(NaN(data));
</script>
</head>
</html>
当前回答
好的,得到负号,因为没有描述我的例子,所以更多的例子:):
我使用正则表达式和测试方法:
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);
其他回答
Lodash https://lodash.com/docs#isInteger(自4.0.0起)有函数检查变量是否为整数:
_.isInteger(3);
// → true
_.isInteger(Number.MIN_VALUE);
// → false
_.isInteger(Infinity);
// → false
_.isInteger('3');
// → false
Number.isInteger()似乎是可行的方法。
MDN还为不支持Number.isInteger()的浏览器提供了以下填充,主要是所有版本的IE。
链接到MDN页面
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
检查变量是否等于相同的变量四舍五入为整数,就像这样:
if(Math.round(data) != data) {
alert("Variable is not an integer!");
}
你可以使用regexp:
function isInteger(n) {
return (typeof n == 'number' && /^-?\d+$/.test(n+''));
}
从http://www.toptal.com/javascript/interview-questions:
function isInteger(x) { return (x^0) === x; }
我发现这是最好的方法。