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:23

Lodash https://lodash.com/docs#isInteger (since 4.0.0) has function to check if variable is an integer:

_.isInteger(3);
// → true

_.isInteger(Number.MIN_VALUE);
// → false

_.isInteger(Infinity);
// → false

_.isInteger('3');
// → false
查看更多
皆成旧梦
3楼-- · 2019-01-01 03:24

Ok got minus, cause didn't describe my example, so more examples:):

I use regular expression and test method:

var isInteger = /^[0-9]\d*$/;

isInteger.test(123); //true
isInteger.test('123'); // true
isInteger.test('sdf'); //false
isInteger.test('123sdf'); //false

// If u want to avoid string value:
typeof testVal !== 'string' && isInteger.test(testValue);
查看更多
浅入江南
4楼-- · 2019-01-01 03:24
function isInteger(argument) { return argument == ~~argument; }

Usage:

isInteger(1);     // true<br>
isInteger(0.1);   // false<br>
isInteger("1");   // true<br>
isInteger("0.1"); // false<br>

or:

function isInteger(argument) { return argument == argument + 0 && argument == ~~argument; }

Usage:

isInteger(1);     // true<br>
isInteger(0.1);   // false<br>
isInteger("1");   // false<br>
isInteger("0.1"); // false<br>
查看更多
明月照影归
5楼-- · 2019-01-01 03:25

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
查看更多
谁念西风独自凉
6楼-- · 2019-01-01 03:28
var x = 1.5;
if(!isNaN(x)){
 console.log('Number');
 if(x % 1 == 0){
   console.log('Integer');
 }
}else {
 console.log('not a number');
}
查看更多
栀子花@的思念
7楼-- · 2019-01-01 03:29

First off, NaN is a "number" (yes I know it's weird, just roll with it), and not a "function".

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);
查看更多
登录 后发表回答