我如何检查如果一个变量是一个整数在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(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
}
其他回答
我必须检查一个变量(字符串或数字)是否为整数,我使用了这个条件:
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。
你可以使用regexp:
function isInteger(n) {
return (typeof n == 'number' && /^-?\d+$/.test(n+''));
}
试试下面的功能:
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
你可以tryNumber.isInteger(Number(value))如果value可能是一个字符串形式的整数,例如var value = "23",你想要这个值为true。避免尝试Number.isInteger(parseInt(value)),因为这并不总是返回正确的值。例如,如果var value = "23abc",并且你使用parseInt实现,它仍然会返回true。
但是如果你想要严格的整数值,那么可能Number.isInteger(value)就可以了。
ECMA-262 6.0 (ES6)标准包括编号。isInteger函数。
为了增加对旧浏览器的支持,我强烈建议使用强大的和社区支持的解决方案:
https://github.com/paulmillr/es6-shim
这是一个纯粹的ES6 JS polyfills库。
注意,这个库需要es5-shim,只需遵循README.md即可。