本文翻译自:How to check if a variable is an integer in JavaScript?
How do I check if a variable is an integer in JavaScript, and throw an alert if it isn't? 如何检查JavaScript中的变量是否为整数,如果不是,则引发警报? I tried this, but it doesn't work: 我试过了,但是不起作用:
<html>
<head>
<script type="text/javascript">
var data = 22;
alert(NaN(data));
</script>
</head>
</html>
#1楼
参考:https://stackoom.com/question/zPdA/如何在JavaScript中检查变量是否为整数
#2楼
Check if the variable is equal to that same variable rounded to an integer, like this: 检查变量是否等于舍入为整数的相同变量,如下所示:
if(Math.round(data) != data) {
alert("Variable is not an integer!");
}
#3楼
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);
#4楼
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.
}
}
#5楼
Use the === operator ( strict equality ) as below, 使用===运算符( 严格等于 ),如下所示,
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")
#6楼
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
}