我想用最简单的故障安全测试来检查JavaScript中的字符串是否是正整数。
isNaN(str)为所有非整数值返回true, parseInt(str)为浮点字符串返回整数,如“2.5”。我也不想使用一些jQuery插件。
我想用最简单的故障安全测试来检查JavaScript中的字符串是否是正整数。
isNaN(str)为所有非整数值返回true, parseInt(str)为浮点字符串返回整数,如“2.5”。我也不想使用一些jQuery插件。
当前回答
(~~a == a),其中a是字符串。
其他回答
这几乎是一个重复的问题:
在JavaScript中验证十进制- IsNumeric()
答案是:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
所以,一个正整数是:
function isPositiveInteger(n) {
var floatN = parseFloat(n);
return !isNaN(floatN) && isFinite(n) && floatN > 0
&& floatN % 1 == 0;
}
这就是我如何验证一个字符串是一个正整数。
瓦尔str =“123”; var str1 =“1.5”; var str2 = -123; 控制台(“is str positive integer:”,数字.isInteger(数字(str)和数字(str) > 0) 控制台(“is str1正图:”,数字.isInteger(数字(str1)和数字(str1) > 0) 控制台(“is str2正图:”,isInteger(数字(str2): && Number(str2) > 0)
适用于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);
}
(~~a == a),其中a是字符串。
我的标准需要在@VisioN的答案上进行一些额外的检查。
不是负数,包括-0 不是小数部分为零的浮点数——0.0,1.000000 不是指数形式的数字,1e10
我发现这对于验证Express路由器的路由参数很有用。例如/书/:bookId
Code
/**
* Validate that a string is a positive integer
* Excludes float numbers with a zero decimal part, exponential notation and negative 0
* @param n
* @returns {boolean}
*/
function isStrictlyPositiveInteger(n) {
const nString = n.toString(), nInt = parseInt(n), nFloat = parseFloat(n);
// if a negative number (works on -0)
if (nString.charAt(0) === '-') {
return false;
}
// if an exponential like 1e10
if (nString.indexOf('e') > -1) {
return false;
}
// if a float number with a zero decimal part e.g 0.0
if ((nFloat === nInt) && (nString.indexOf('.') > -1)) {
return false;
}
// if a positive integer
// https://stackoverflow.com/a/10835227/8470877
return (0 === n % (!isNaN(nFloat) && 0 <= ~~n));
}
测试
"0" : true
"23" : true
"-10" : false
"10.30" : false
"-40.1" : false
"string" : false
"1234567890" : true
"129000098131766699.1" : false
"-1e10" : false
"1e10" : false
"1edf" : false
" " : false
"" : false
"0.01" : false
"0.00" : false
"-0" : false
"-0.0" : false
"0." : false
"-" : false
".1" : false