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


当前回答

你可以按照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。。。

这里有一个优雅的单行线来检查sNum是否是有效的数值。该代码也已针对各种输入进行了测试。

// returns True if sNum is a numeric value    
!!sNum && !isNaN(+sNum.replace(/\s|\$/g, ''));  

向@gman提示错误。

我最近写了一篇关于如何确保变量是有效数字的文章: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
}

我喜欢这种简单。

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有点模棱两可,很难理解。

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

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