我如何检查如果一个变量是一个整数在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>
当前回答
检查变量是否等于相同的变量四舍五入为整数,就像这样:
if(Math.round(data) != data) {
alert("Variable is not an integer!");
}
其他回答
试试下面的功能:
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
我必须检查一个变量(字符串或数字)是否为整数,我使用了这个条件:
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。
if(Number.isInteger(Number(data))){
//-----
}
我的方法:
a >= 1e+21→只适用于非常大的数字。这将肯定涵盖所有情况,不像本讨论中提供的其他解决方案。
A === (A |0)→如果给定函数的实参与按位转换的值完全相同(===),则意味着实参是一个整数。
A |0→对于A的任何非数字值都返回0,如果A确实是数字,它将去掉小数点后的所有数字,因此1.0001将变成1
const isInteger = n => n >= 1e+21 ? true : n === (n|0); // tests: [ [1, true], [1000000000000000000000, true], [4e2, true], [Infinity, true], [1.0, true], [1.0000000000001, false], [0.1, false], ["0", false], ["1", false], ["1.1", false], [NaN, false], [[], false], [{}, false], [true, false], [false, false], [null, false], [undefined, false], ].forEach(([test, expected]) => console.log( isInteger(test) === expected, typeof test, test ) )
使用===运算符(严格相等),如下所示:
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")