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


当前回答

它对TypeScript无效,因为:

声明函数isNaN(数字:数字):布尔值;

对于TypeScript,您可以使用:

/^\d+$/.测试(键)

其他回答

我的尝试有点混乱,Pherhaps不是最好的解决方案

function isInt(a){
    return a === ""+~~a
}


console.log(isInt('abcd'));         // false
console.log(isInt('123a'));         // false
console.log(isInt('1'));            // true
console.log(isInt('0'));            // true
console.log(isInt('-0'));           // false
console.log(isInt('01'));           // false
console.log(isInt('10'));           // true
console.log(isInt('-1234567890'));  // true
console.log(isInt(1234));           // false
console.log(isInt('123.4'));        // false
console.log(isInt(''));             // false

// other types then string returns false
console.log(isInt(5));              // false
console.log(isInt(undefined));      // false
console.log(isInt(null));           // false
console.log(isInt('0x1'));          // false
console.log(isInt(Infinity));       // false

我的解决方案:

// 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;
 };

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

在我的应用程序中,我们只允许a-z a-z和0-9字符。我发现上面使用“字符串%1==0”的答案有效,除非字符串以0xnn开头(如0x10),然后当我们不希望它返回时,它会将其返回为数字。我的数字检查中的以下简单陷阱似乎在我们的特定情况下起到了作用。

function isStringNumeric(str_input){   
    //concat a temporary 1 during the modulus to keep a beginning hex switch combination from messing us up   
    //very simple and as long as special characters (non a-z A-Z 0-9) are trapped it is fine   
    return '1'.concat(str_input) % 1 === 0;}

警告:这可能是在利用Javascript和Actionscript中的一个长期错误[Number(“1”+the_string)%1==0)],我无法对此进行说明,但这正是我们所需要的。

也许有一两个人遇到这个问题,他们需要比平时更严格的检查(就像我一样)。在这种情况下,这可能很有用:

if(str === String(Number(str))) {
  // it's a "perfectly formatted" number
}

当心这将拒绝类似于.1、40.000、080、00.1的字符串。它非常挑剔——字符串必须匹配数字的“最最小完美形式”才能通过测试。

它使用String和Number构造函数将字符串转换为一个数字,然后再次返回,从而检查JavaScript引擎的“完美最小形式”(用初始Number构造函数转换为的形式)是否与原始字符串匹配。

在将参数传递给其构造函数时,可以使用Number的结果。

如果参数(字符串)不能转换为数字,它将返回NaN,因此您可以确定提供的字符串是否为有效数字。

注意:当传递空字符串或'\t\t'和'\n\t'作为Number时,将返回0;传递true将返回1,传递false将返回0。

    Number('34.00') // 34
    Number('-34') // -34
    Number('123e5') // 12300000
    Number('123e-5') // 0.00123
    Number('999999999999') // 999999999999
    Number('9999999999999999') // 10000000000000000 (integer accuracy up to 15 digit)
    Number('0xFF') // 255
    Number('Infinity') // Infinity  

    Number('34px') // NaN
    Number('xyz') // NaN
    Number('true') // NaN
    Number('false') // NaN

    // cavets
    Number('    ') // 0
    Number('\t\t') // 0
    Number('\n\t') // 0