我如何检查如果一个变量是一个整数在JavaScript,并抛出一个警告,如果它不是?我试过了,但不管用:

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

当前回答

Lodash https://lodash.com/docs#isInteger(自4.0.0起)有函数检查变量是否为整数:

_.isInteger(3);
// → true

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

_.isInteger(Infinity);
// → false

_.isInteger('3');
// → false

其他回答

你也可以试试这种方法

var data = 22;
if (Number.isInteger(data)) {
    console.log("integer");
 }else{
     console.log("not an integer");
 }

or

if (data === parseInt(data, 10)){
    console.log("integer");
}else{
    console.log("not an integer");
}

使用|运算符:

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

所以,一个测试函数可能是这样的:

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

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

  return true;
};

这要看情况,你是否也想将字符串转换为潜在整数?

这样做:

function isInt(value) {
  return !isNaN(value) && 
         parseInt(Number(value)) == value && 
         !isNaN(parseInt(value, 10));
}

按位操作

简单的解析和检查

function isInt(value) {
  var x = parseFloat(value);
  return !isNaN(value) && (x | 0) === x;
}

短路并保存解析操作:

function isInt(value) {
  if (isNaN(value)) {
    return false;
  }
  var x = parseFloat(value);
  return (x | 0) === x;
}

或者两者同时出现:

function isInt(value) {
  return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
}

测试:

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

这是小提琴:http://jsfiddle.net/opfyrqwp/28/

性能

测试表明,短路解决方案具有最佳的性能(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;
}

下面是一个基准: http://jsben.ch/#/htLVw

如果你喜欢更短的钝角短路形式:

function isInt(value) {
  var x;
  return isNaN(value) ? !1 : (x = parseFloat(value), (0 | x) === x);
}

当然了,我建议让这个小工具来处理。

你可以使用这个函数:

function isInteger(value) {
    return (value == parseInt(value));
}

即使值是包含整数值的字符串,它也将返回true。 因此,结果将是:

alert(isInteger(1)); // true
alert(isInteger(1.2)); // false
alert(isInteger("1")); // true
alert(isInteger("1.2")); // false
alert(isInteger("abc")); // false

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

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

我发现这是最好的方法。