我想用最简单的故障安全测试来检查JavaScript中的字符串是否是正整数。

isNaN(str)为所有非整数值返回true, parseInt(str)为浮点字符串返回整数,如“2.5”。我也不想使用一些jQuery插件。


当前回答

适用于node和90%以上浏览器(IE和Opera Mini除外)的现代解决方案是使用Number。isInteger后跟一个简单的正检查。

Number.isInteger(x) && x > 0

这是在ECMAScript 2015中完成的。

function isPositiveInteger(x) {
    return Number.isInteger(x) && x > 0
}

Polyfil是:

Number.isInteger = Number.isInteger || function(value) {
  return typeof value === 'number' && 
    isFinite(value) && 
    Math.floor(value) === value;
};

如果你需要支持字符串或数字形式的输入,那么你可以使用这个函数,在所有现有的答案(2/1/2018)在某种形式的输入上失败后,我写了一个大型测试套件。

function isPositiveInteger(v) {
  var i;
  return v && (i = parseInt(v)) && i > 0 && (i === v || ''+i === v);
}

其他回答

我的问题基本上是相同的:检查用户输入的数字是否为整数和正数。

我们的朋友Levi的代码和响应是我迄今为止在整个互联网上发现的最好的,在处理错误方面令人满意。

我在网站(https://bobbyhadz.com/blog/javascript-check-if-string-is-positive-integer):)上找到了下面的代码

function isPositiveInteger(str) {
   if (typeof str !== 'string') {
     return false;
   }
   const num = Number(str);
   if (Number.isInteger(num) && num > 0) {
     return true;
   }
   return false;
}

但是,对于1e10,它不能正确返回。

(~~a == a),其中a是字符串。

看起来正则表达式是可行的:

var isInt = /^\+?\d+$/.test('the string');

我的函数检查数字是否为+ve,也可以是十进制值。

       function validateNumeric(numValue){
            var value = parseFloat(numValue);
            if (!numValue.toString().match(/^[-]?\d*\.?\d*$/)) 
                    return false;
            else if (numValue < 0) {
                return false;
            }
            return true;        
        }

ES6:

Number.isInteger(Number(theNumberString)) && Number(theNumberString) > 0