如何在JavaScript中检查变量是否为整数?

本文翻译自: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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值