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


当前回答

如果你喜欢一种巧妙的方式,并且你喜欢让同事感到困惑,你可以使用:

const isNumeric = str => parseFloat(str) === parseFloat(str)

证明:

const isNumeric=str=>parseFloat(str)===parseFloit(str)console.log(isNumeric(“10”))console.log(isNumeric('-10.2'))console.log(isNumeric('15abc'))console.log(isNumeric('0.0001'))console.log(isNumeric('abc'))console.log(isNumeric('abc123'))

其他回答

我最近写了一篇关于如何确保变量是有效数字的文章:https://github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md本文解释了如何确保浮点或整数,如果这很重要(+x vs ~~x)。

本文假设变量是一个字符串或一个数字开头,trim可用/polyfulled。将其扩展到处理其他类型也不难。这是它的肉:

// Check for a valid float
if (x == null
    || ("" + x).trim() === ""
    || isNaN(+x)) {
    return false;  // not a float
}

// Check for a valid integer
if (x == null
    || ("" + x).trim() === ""
    || ~~x !== +x) {
    return false;  // not an integer
}

你可以按照RegExp的方式:

var num = "987238";

if(num.match(/^-?\d+$/)){
  //valid integer (positive or negative)
}else if(num.match(/^\d+\.\d+$/)){
  //valid float
}else{
  //not valid number
}

尝试isNan函数:

isNaN()函数确定值是否为非法数字(Not-a-number)。如果值等于NaN,则此函数返回true。否则返回false。此函数与特定于Number的Number.isNaN()方法不同。全局isNaN()函数将测试值转换为Number,然后对其进行测试。Number.isNan()不会将值转换为Number,并且对于任何非Number类型的值都不会返回true。。。

我在Angular中使用了这个函数

 isNumeric(value: string): boolean {
             let valueToNumber = Number(value);
             var result = typeof valueToNumber == 'number' ;
             if(valueToNumber.toString() == 'NaN')
             {
                result = false;
             }
             return result;
          }

检查JS中的数字:

检查是否为数字的最佳方法:是有限的(20)//真的从字符串中读取值。CSS*:parseInt('2.5rem')//2parseFloat('2.5rem')//2.5 对于整数:isInteger(23/0)//错误如果值为NaN:isNaN(20)//错误