(Built-in) way in JavaScript to check if a string is a valid number

前端 未结 30 3837
-上瘾入骨i
-上瘾入骨i 2020-11-22 01:54

I\'m hoping there\'s something in the same conceptual space as the old VB6 IsNumeric() function?

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 02:28

    If anyone ever gets this far down, I spent some time hacking on this trying to patch moment.js (https://github.com/moment/moment). Here's something that I took away from it:

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

    Handles the following cases:

    True! :

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

    False! :

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

    Ironically, the one I am struggling with the most:

    isNumeric(new Number(1)) => false
    

    Any suggestions welcome. :]

提交回复
热议问题