我如何检查如果一个变量是一个整数在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>
当前回答
在ES6中,为数字对象添加了2个新方法。
其中Number.isInteger()方法如果参数为整数则返回true,否则返回false。
重要注意:对于可以表示为整数的浮点数,该方法也将返回true。例如:5.0(因为它恰好等于5)
用法示例:
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(-100000); // true
Number.isInteger(99999999999999999999999); // true
Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false
Number.isInteger(NaN); // false
Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false
Number.isInteger('10'); // false
Number.isInteger(true); // false
Number.isInteger(false); // false
Number.isInteger([1]); // false
Number.isInteger(5.0); // true
Number.isInteger(5.000000000000001); // false
Number.isInteger(5.0000000000000001); // true
其他回答
大整数(bigint)呢?
大多数这些答案在大整数(253或更大)上失败:(x | 0) === x),测试typeof x === 'number',常规int函数(例如parseInt),常规算术在大整数上失败。这可以通过使用BigInt来解决。
我将几个答案编译成一个代码片段以显示结果。对于大整数,大多数完全失败,而其他的则可以,除非传入BigInt类型(例如1n)。我没有包括重复的答案,也没有任何答案,允许小数或不试图测试类型)
// these all fail n = 1000000000000000000000000000000 b = 1n // These all fail on large integers //https://stackoverflow.com/a/14636652/3600709 console.log('fail',1,n === parseInt(n, 10)) //https://stackoverflow.com/a/14794066/3600709 console.log('fail',2,!isNaN(n) && parseInt(Number(n)) == n && !isNaN(parseInt(n, 10))) console.log('fail',2,!isNaN(n) && (parseFloat(n) | 0) === parseFloat(n)) console.log('fail',2,!isNaN(n) && (function(x) { return (x | 0) === x; })(parseFloat(n))) //https://stackoverflow.com/a/21742529/3600709 console.log('fail',3,n == ~~n) //https://stackoverflow.com/a/28211631/3600709 console.log('fail',4,!isNaN(n) && parseInt(n) == parseFloat(n)) //https://stackoverflow.com/a/41854178/3600709 console.log('fail',5,String(parseInt(n, 10)) === String(n)) // These ones work for integers, but not BigInt types (e.g. 1n) //https://stackoverflow.com/a/14636725/3600709 console.log('partial',1,typeof n==='number' && (n%1)===0) // this one works console.log('partial',1,typeof b==='number' && (b%1)===0) // this one fails //https://stackoverflow.com/a/27424770/3600709 console.log('partial',2,Number.isInteger(n)) // this one works console.log('partial',2,Number.isInteger(b)) // this one fails //https://stackoverflow.com/a/14636638/3600709 console.log('partial',3,n % 1 === 0) console.log('partial',3,b % 1 === 0) // gives uncaught type on BigInt
检查类型
如果你真的想测试输入值的类型,以确保它是一个整数,可以使用下面的方法:
function isInt(value) {
try {
BigInt(value)
return !['string','object','boolean'].includes(typeof value)
} catch(e) {
return false
}
}
function isInt(value) { try { BigInt(value) return !['string','object','boolean'].includes(typeof value) } catch(e) { return false } } console.log('--- should be false') console.log(isInt(undefined)) console.log(isInt('')) console.log(isInt(null)) console.log(isInt({})) console.log(isInt([])) console.log(isInt(1.1e-1)) console.log(isInt(1.1)) console.log(isInt(true)) console.log(isInt(NaN)) console.log(isInt('1')) console.log(isInt(function(){})) console.log(isInt(Infinity)) console.log('--- should be true') console.log(isInt(10)) console.log(isInt(0x11)) console.log(isInt(0)) console.log(isInt(-10000)) console.log(isInt(100000000000000000000000000000000000000)) console.log(isInt(1n))
不检查类型
如果你不关心传入类型是否实际上是布尔值、字符串等转换成数字,那么只需使用以下方法:
function isInt(value) {
try {
BigInt(value)
return true
} catch(e) {
return false
}
}
function isInt(value) { try { BigInt(value) return true } catch(e) { return false } } console.log('--- should be false') console.log(isInt(undefined)) console.log(isInt(null)) console.log(isInt({})) console.log(isInt(1.1e-1)) console.log(isInt(1.1)) console.log(isInt(NaN)) console.log(isInt(function(){})) console.log(isInt(Infinity)) console.log('--- should be true') console.log(isInt(10)) console.log(isInt(0x11)) console.log(isInt(0)) console.log(isInt(-10000)) console.log(isInt(100000000000000000000000000000000000000)) console.log(isInt(1n)) // gets converted to number console.log(isInt('')) console.log(isInt([])) console.log(isInt(true)) console.log(isInt('1'))
你也可以试试这种方法
var data = 22;
if (Number.isInteger(data)) {
console.log("integer");
}else{
console.log("not an integer");
}
or
if (data === parseInt(data, 10)){
console.log("integer");
}else{
console.log("not an integer");
}
假设你对问题中的变量一无所知,你应该采用这种方法:
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。
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