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


当前回答

这里是isNumber实现的高性能(2.5*10^7迭代/s@3.8GHz Haswell)版本。它适用于我能找到的每个测试用例(包括符号):

var isNumber = (function () {
  var isIntegerTest = /^\d+$/;
  var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];
  function hasLeading0s (s) {
    return !(typeof s !== 'string' ||
    s.length < 2 ||
    s[0] !== '0' ||
    !isDigitArray[s[1]] ||
    isIntegerTest.test(s));
  }
  var isWhiteSpaceTest = /\s/;
  return function isNumber (s) {
    var t = typeof s;
    var n;
    if (t === 'number') {
      return (s <= 0) || (s > 0);
    } else if (t === 'string') {
      n = +s;
      return !((!(n <= 0) && !(n > 0)) || n === '0' || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));
    } else if (t === 'object') {
      return !(!(s instanceof Number) || ((n = +s), !(n <= 0) && !(n > 0)));
    }
    return 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;
 };

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

这是基于之前的一些回答和评论。以下内容涵盖了所有边缘情况,也相当简洁:

const isNumRegEx = /^-?(\d*\.)?\d+$/;

function isNumeric(n, allowScientificNotation = false) {
    return allowScientificNotation ? 
                !Number.isNaN(parseFloat(n)) && Number.isFinite(n) :
                isNumRegEx.test(n);
}

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

科学记数法。

!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);
  }

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

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

2019:实用且严格的数字有效性检查

通常,“有效数”是指不包括NaN和Infinity的Javascript数,即“有限数”。

要检查值的数值有效性(例如来自外部源),可以在ESlint Airbnb样式中定义:

/**
 * Returns true if 'candidate' is a finite number or a string referring (not just 'including') a finite number
 * To keep in mind:
 *   Number(true) = 1
 *   Number('') = 0
 *   Number("   10  ") = 10
 *   !isNaN(true) = true
 *   parseFloat('10 a') = 10
 *
 * @param {?} candidate
 * @return {boolean}
 */
function isReferringFiniteNumber(candidate) {
  if (typeof (candidate) === 'number') return Number.isFinite(candidate);
  if (typeof (candidate) === 'string') {
    return (candidate.trim() !== '') && Number.isFinite(Number(candidate));
  }
  return false;
}

并以如下方式使用:

if (isReferringFiniteNumber(theirValue)) {
  myCheckedValue = Number(theirValue);
} else {
  console.warn('The provided value doesn\'t refer to a finite number');
}