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


当前回答

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

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

向@gman提示错误。

其他回答

它对TypeScript无效,因为:

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

对于TypeScript,您可以使用:

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

尝试isNan函数:

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

我的解决方案:

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

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

我喜欢这种简单。

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

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

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'))