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


当前回答

省去了寻找“内置”解决方案的麻烦。

没有一个好的答案,而这篇文章中获得极大支持的答案是错误的。

npm安装是数字

在JavaScript中,可靠地检查值是否为数字并不总是那么简单。开发人员通常使用+、-或Number()将字符串值转换为数字(例如,当从用户输入、正则表达式匹配、解析器等返回值时)。但有许多非直觉的边缘情况会产生意想不到的结果:

console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+'   '); //=> 0
console.log(typeof NaN); //=> 'number'

其他回答

2020年10月2日:请注意,许多简单的方法都充满了微妙的错误(例如空白、隐式部分解析、基数、数组强制等),这里的许多答案都没有考虑到。以下实现可能适用于您,但请注意,它不适用于小数点“.”以外的数字分隔符:

function isNumeric(str) {
  if (typeof str != "string") return false // we only process strings!  
  return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
         !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}

要检查变量(包括字符串)是否是数字,请检查它是否不是数字:

无论变量内容是字符串还是数字,这都是有效的。

isNaN(num)         // returns true if the variable does NOT contain a valid number

示例

isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true
isNaN('')          // false
isNaN(' ')         // false
isNaN(false)       // false

当然,如果需要,您可以否定这一点。例如,要实现您给出的IsNumeric示例:

function isNumeric(num){
  return !isNaN(num)
}

要将包含数字的字符串转换为数字,请执行以下操作:

仅当字符串仅包含数字字符时有效,否则返回NaN。

+num               // returns the numeric value of the string, or NaN 
                   // if the string isn't purely numeric characters

示例

+'12'              // 12
+'12.'             // 12
+'12..'            // NaN
+'.12'             // 0.12
+'..12'            // NaN
+'foo'             // NaN
+'12px'            // NaN

将字符串松散地转换为数字

用于将“12px”转换为12,例如:

parseInt(num)      // extracts a numeric value from the 
                   // start of the string, or NaN.

示例

parseInt('12')     // 12
parseInt('aaa')    // NaN
parseInt('12px')   // 12
parseInt('foo2')   // NaN      These last three may
parseInt('12a5')   // 12       be different from what
parseInt('0x10')   // 16       you expected to see.

浮子

请记住,与+num不同,parseInt(顾名思义)将通过截断小数点后的所有内容来将浮点转换为整数(如果因为这种行为而希望使用parseInt(),那么最好使用另一种方法):

+'12.345'          // 12.345
parseInt(12.345)   // 12
parseInt('12.345') // 12

空字符串

空字符串可能有点违背直觉+num将空字符串或带空格的字符串转换为零,isNaN()假设相同:

+''                // 0
+'   '             // 0
isNaN('')          // false
isNaN('   ')       // false

但parseInt()不同意:

parseInt('')       // NaN
parseInt('   ')    // NaN

parseInt(),但要注意,这个函数有点不同,例如,它为parseInt返回100(“100px”)。

我使用这个函数作为表单验证工具,我不希望用户能够编写指数函数,所以我想出了这个函数:

<script>

    function isNumber(value, acceptScientificNotation) {

        if(true !== acceptScientificNotation){
            return /^-{0,1}\d+(\.\d+)?$/.test(value);
        }

        if (true === Array.isArray(value)) {
            return false;
        }
        return !isNaN(parseInt(value, 10));
    }


    console.log(isNumber(""));              // false
    console.log(isNumber(false));           // false
    console.log(isNumber(true));            // false
    console.log(isNumber("0"));             // true
    console.log(isNumber("0.1"));           // true
    console.log(isNumber("12"));            // true
    console.log(isNumber("-12"));           // true
    console.log(isNumber(-45));             // true
    console.log(isNumber({jo: "pi"}));      // false
    console.log(isNumber([]));              // false
    console.log(isNumber([78, 79]));        // false
    console.log(isNumber(NaN));             // false
    console.log(isNumber(Infinity));        // false
    console.log(isNumber(undefined));       // false
    console.log(isNumber("0,1"));           // false



    console.log(isNumber("1e-1"));          // false
    console.log(isNumber("1e-1", true));    // true
</script>

您可以使用类型(如流库)来进行静态编译时检查。当然,对于用户输入并不是很有用。

// @flow

function acceptsNumber(value: number) {
  // ...
}

acceptsNumber(42);       // Works!
acceptsNumber(3.14);     // Works!
acceptsNumber(NaN);      // Works!
acceptsNumber(Infinity); // Works!
acceptsNumber("foo");    // Error!

如果有人对此感到失望的话,我花了一些时间来修补moment.js(https://github.com/moment/moment). 我从中得到了一些东西:

function isNumeric(val) {
    var _val = +val;
    return (val !== val + 1) //infinity check
        && (_val === +val) //Cute coercion check
        && (typeof val !== 'object') //Array/object check
}

处理以下情况:

真!:

isNumeric("1"))
isNumeric(1e10))
isNumeric(1E10))
isNumeric(+"6e4"))
isNumeric("1.2222"))
isNumeric("-1.2222"))
isNumeric("-1.222200000000000000"))
isNumeric("1.222200000000000000"))
isNumeric(1))
isNumeric(0))
isNumeric(-0))
isNumeric(1010010293029))
isNumeric(1.100393830000))
isNumeric(Math.LN2))
isNumeric(Math.PI))
isNumeric(5e10))

错误!:

isNumeric(NaN))
isNumeric(Infinity))
isNumeric(-Infinity))
isNumeric())
isNumeric(undefined))
isNumeric('[1,2,3]'))
isNumeric({a:1,b:2}))
isNumeric(null))
isNumeric([1]))
isNumeric(new Date()))

具有讽刺意味的是,我最纠结的是:

isNumeric(new Number(1)) => false

欢迎提出任何建议。:]