How to check if a variable is an integer in JavaSc

2019-01-01 02:47发布

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:

<html>
    <head>
        <script type="text/javascript">
            var data = 22;
            alert(NaN(data));
        </script>
    </head>
</html>

标签: javascript
30条回答
听够珍惜
2楼-- · 2019-01-01 03:33

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
}
查看更多
何处买醉
3楼-- · 2019-01-01 03:35

Besides, Number.isInteger(). Maybe Number.isSafeInteger() is another option here by using the ES6-specified.

To polyfill Number.isSafeInteger(..) in pre-ES6 browsers:

Number.isSafeInteger = Number.isSafeInteger || function(num) {
    return typeof num === "number" && 
           isFinite(num) && 
           Math.floor(num) === num &&
           Math.abs( num ) <= Number.MAX_SAFE_INTEGER;
};
查看更多
听够珍惜
4楼-- · 2019-01-01 03:36

Use the | operator:

(5.3 | 0) === 5.3 // => false
(5.0 | 0) === 5.0 // => true

So, a test function might look like this:

var isInteger = function (value) {
  if (typeof value !== 'number') {
    return false;
  }

  if ((value | 0) !== value) {
    return false;
  }

  return true;
};
查看更多
美炸的是我
5楼-- · 2019-01-01 03:37

Be careful while using

num % 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(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

查看更多
初与友歌
6楼-- · 2019-01-01 03:38

From http://www.toptal.com/javascript/interview-questions:

function isInteger(x) { return (x^0) === x; } 

Found it to be the best way to do this.

查看更多
刘海飞了
7楼-- · 2019-01-01 03:39
if(Number.isInteger(Number(data))){
    //-----
}
查看更多
登录 后发表回答