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


当前回答

这是一种检查变量是否不是数字的可能方法:

(isNaN(foo) || ((foo !== 0) && (!foo)))

这意味着foo是假的,但不同于0,或者isNaN(foo)是真的。

执行这种检查的另一种方法是

!isNaN(parseFloat(foo))

其他回答

老问题,但给出的答案中缺少几点。

科学记数法。

!isNaN('e+30')是正确的,但在大多数情况下,当人们要求数字时,他们不想匹配像1e+30这样的数字。

大浮点数的行为可能很奇怪

观察(使用Node.js):

> var s = Array(16 + 1).join('9')
undefined
> s.length
16
> s
'9999999999999999'
> !isNaN(s)
true
> Number(s)
10000000000000000
> String(Number(s)) === s
false
>

另一方面:

> var s = Array(16 + 1).join('1')
undefined
> String(Number(s)) === s
true
> var s = Array(15 + 1).join('9')
undefined
> String(Number(s)) === s
true
>

因此,如果期望String(Number(s))==s,那么最好将字符串限制在最多15位(省略前导零后)。

无穷

> typeof Infinity
'number'
> !isNaN('Infinity')
true
> isFinite('Infinity')
false
>

考虑到所有这些,检查给定字符串是否为满足以下所有条件的数字:

非科学记数法可预测地转换为数字并返回到字符串有限的

这不是一项容易的任务。下面是一个简单的版本:

  function isNonScientificNumberString(o) {
    if (!o || typeof o !== 'string') {
      // Should not be given anything but strings.
      return false;
    }
    return o.length <= 15 && o.indexOf('e+') < 0 && o.indexOf('E+') < 0 && !isNaN(o) && isFinite(o);
  }

然而,即使是这一点也远未完成。这里不处理前导零,但它们确实会破坏长度测试。

我的尝试有点混乱,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

在我的应用程序中,我们只允许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)],我无法对此进行说明,但这正是我们所需要的。

报价:

isNaN(num)//如果变量不包含有效数字,则返回true

如果您需要检查前导/尾随空格,则不完全正确-例如,当需要一定数量的数字时,并且您需要获得例如“1111”而不是“111”或“111”以获得PIN输入。

更好使用:

var num = /^\d+$/.test(num)

它对TypeScript无效,因为:

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

对于TypeScript,您可以使用:

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