我希望在与旧的VB6 IsNumeric()函数相同的概念空间中有什么东西?


当前回答

我的解决方案:

// returns true for positive ints; 
// no scientific notation, hexadecimals or floating point dots

var isPositiveInt = function(str) { 
   var result = true, chr;
   for (var i = 0, n = str.length; i < n; i++) {
       chr = str.charAt(i);
       if ((chr < "0" || chr > "9") && chr != ",") { //not digit or thousands separator
         result = false;
         break;
       };
       if (i == 0 && (chr == "0" || chr == ",")) {  //should not start with 0 or ,
         result = false;
         break;
       };
   };
   return result;
 };

您可以在循环中添加其他条件,以满足您的特定需求。

其他回答

如果您只是想检查字符串是否为整数(无小数位数),正则表达式是一个很好的方法。其他方法(如isNaN)对于如此简单的事情来说过于复杂。

function isNumeric(value) {
    return /^-?\d+$/.test(value);
}

console.log(isNumeric('abcd'));         // false
console.log(isNumeric('123a'));         // false
console.log(isNumeric('1'));            // true
console.log(isNumeric('1234567890'));   // true
console.log(isNumeric('-23'));          // true
console.log(isNumeric(1234));           // true
console.log(isNumeric(1234n));          // true
console.log(isNumeric('123.4'));        // false
console.log(isNumeric(''));             // false
console.log(isNumeric(undefined));      // false
console.log(isNumeric(null));           // false

要仅允许正整数,请使用以下命令:

function isNumeric(value) {
    return /^\d+$/.test(value);
}

console.log(isNumeric('123'));          // true
console.log(isNumeric('-23'));          // false

PFB工作溶液:

 function(check){ 
    check = check + "";
    var isNumber =   check.trim().length>0? !isNaN(check):false;
    return isNumber;
    }

我认为isFinite()对所有人来说都是最好的。

设a=isFinite('abc')//false;设b=isFinite('123')//true;设c=isFinite('12a')//false;控制台日志(a、b、c)

我是这样做的:

function isString(value)
{
    return value.length !== undefined;
}
function isNumber(value)
{
    return value.NaN !== undefined;
}

当然,如果您传递其他定义了“length”的对象,isString()将在这里出错。

我喜欢这种简单。

Number.isNaN(Number(value))

以上是常规的Javascript,但我将其与typescript类型保护器一起用于智能类型检查。这对于类型脚本编译器提供正确的智能感知和无类型错误非常有用。

打字保护装置

警告:请参阅Jeremy在下面的评论。这在某些值上有一些问题,我现在没有时间修复它,但使用typescript类型保护的想法很有用,因此我不会删除此部分。

isNotNumber(value: string | number): value is string {
    return Number.isNaN(Number(this.smartImageWidth));
}
isNumber(value: string | number): value is number {
    return Number.isNaN(Number(this.smartImageWidth)) === false;
}

假设您有一个属性宽度,即number | string。您可能希望根据它是否是字符串来执行逻辑。

var width: number|string;
width = "100vw";

if (isNotNumber(width)) 
{
    // the compiler knows that width here must be a string
    if (width.endsWith('vw')) 
    {
        // we have a 'width' such as 100vw
    } 
}
else 
{
    // the compiler is smart and knows width here must be number
    var doubleWidth = width * 2;    
}

类型保护足够聪明,可以将if语句中的宽度类型限制为ONLY字符串。这允许编译器允许width.endsWith(…),如果类型为string | number,则不允许。

你可以随意调用类型保护器isNotNumber,isNumber,isString,isNotString,但我认为isString有点模棱两可,很难理解。