JavaScript 中如何判断一个变量是否为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14636536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a variable is an integer in JavaScript?
提问by JBa
How do I check if a variable is an integer in JavaScript, and throw an alert if it isn't? I tried this, but it doesn't work:
如何在 JavaScript 中检查变量是否为整数,如果不是则抛出警报?我试过这个,但它不起作用:
<html>
<head>
<script type="text/javascript">
var data = 22;
alert(NaN(data));
</script>
</head>
</html>
采纳答案by pranag
Use the === operator (strict equality) as below,
使用 === 运算符(严格相等)如下,
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")
回答by krisk
That depends, do you also want to cast strings as potential integers as well?
这取决于,您是否也想将字符串也转换为潜在的整数?
This will do:
这将:
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
With Bitwise operations
使用按位运算
Simple parse and check
简单的解析和检查
function isInt(value) {
var x = parseFloat(value);
return !isNaN(value) && (x | 0) === x;
}
Short-circuiting, and saving a parse operation:
短路并保存解析操作:
function isInt(value) {
if (isNaN(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
}
Or perhaps both in one shot:
或者可能同时进行:
function isInt(value) {
return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
}
Tests:
测试:
isInt(42) // true
isInt("42") // true
isInt(4e2) // true
isInt("4e2") // true
isInt(" 1 ") // true
isInt("") // false
isInt(" ") // false
isInt(42.1) // false
isInt("1a") // false
isInt("4e2a") // false
isInt(null) // false
isInt(undefined) // false
isInt(NaN) // false
Here's the fiddle: http://jsfiddle.net/opfyrqwp/28/
这是小提琴:http: //jsfiddle.net/opfyrqwp/28/
Performance
表现
Testing reveals that the short-circuiting solution has the best performance (ops/sec).
测试表明,短路解决方案具有最佳性能(操作数/秒)。
// Short-circuiting, and saving a parse operation
function isInt(value) {
var x;
if (isNaN(value)) {
return false;
}
x = parseFloat(value);
return (x | 0) === x;
}
Here is a benchmark: http://jsben.ch/#/htLVw
这是一个基准:http: //jsben.ch/#/htLVw
If you fancy a shorter, obtuse form of short circuiting:
如果您喜欢更短、更钝的短路形式:
function isInt(value) {
var x;
return isNaN(value) ? !1 : (x = parseFloat(value), (0 | x) === x);
}
Of course, I'd suggest letting the minifier take care of that.
当然,我建议让压缩器来处理。
回答by Blake Regalia
Assuming you don't know anything about the variable in question, you should take this approach:
假设您对相关变量一无所知,您应该采用以下方法:
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
}
To put it simply:
简而言之:
if(typeof data==='number' && (data%1)===0) {
// data is an integer
}
回答by Walter Roman
Number.isInteger()seems to be the way to go.
Number.isInteger()似乎是要走的路。
MDN has also provided the following polyfill for browsers not supporting Number.isInteger(), mainly all versions of IE.
MDN 还为不支持的浏览器提供了以下 polyfill Number.isInteger(),主要是所有版本的 IE。
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
回答by Nope
You could check if the number has a remainder:
您可以检查数字是否有余数:
var data = 22;
if(data % 1 === 0){
// yes it's an integer.
}
Mind you, if your input could also be text and you want to check first it is not, then you can check the type first:
请注意,如果您的输入也可以是文本,而您想先检查它不是,那么您可以先检查类型:
var data = 22;
if(typeof data === 'number'){
// yes it is numeric
if(data % 1 === 0){
// yes it's an integer.
}
}
回答by Marcio Mazzucato
You can use a simple regular expression:
您可以使用一个简单的正则表达式:
function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);
}
回答by Phil
First off, NaN is a "number" (yes I know it's weird, just roll with it), and not a "function".
首先, NaN 是一个“数字”(是的,我知道这很奇怪,只是用它滚动),而不是“函数”。
You need to check both if the type of the variable is a number, and to check for integer I would use modulus.
您需要检查变量的类型是否为数字,并检查整数我将使用模数。
alert(typeof data === 'number' && data%1 == 0);
回答by Jhankar Mahbub
Be careful while using
使用时要小心
num % 1
数量 % 1
empty string ('') or boolean (true or false) will return as integer. You might not want to do that
空字符串 ('') 或布尔值(真或假)将作为整数返回。你可能不想这样做
false % 1 // true
'' % 1 //true
Number.isInteger(data)
Number.isInteger(数据)
Number.isInteger(22); //true
Number.isInteger(22.2); //false
Number.isInteger('22'); //false
build in function in the browser. Dosnt support older browsers
在浏览器中内置功能。不支持旧浏览器
Alternatives:
备择方案:
Math.round(num)=== num
However, Math.round() also will fail for empty string and boolean
但是,Math.round() 也会因空字符串和布尔值而失败
回答by user603749
To check if integer like poster wants:
要检查像海报这样的整数是否需要:
if (+data===parseInt(data)) {return true} else {return false}
notice + in front of data (converts string to number), and === for exact.
注意数据前面的 +(将字符串转换为数字),而 === 表示精确。
Here are examples:
以下是示例:
data=10
+data===parseInt(data)
true
data="10"
+data===parseInt(data)
true
data="10.2"
+data===parseInt(data)
false
回答by guest
if(Number.isInteger(Number(data))){
//-----
}

