Check if character is number?

前端 未结 22 747
误落风尘
误落风尘 2020-12-03 00:29

I need to check whether justPrices[i].substr(commapos+2,1).

The string is something like: \"blabla,120\"

In this case it would check whether \'0

22条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 00:42

    You can use this:

    function isDigit(n) {
        return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
    }
    

    Here, I compared it to the accepted method: http://jsperf.com/isdigittest/5 . I didn't expect much, so I was pretty suprised, when I found out that accepted method was much slower.

    Interesting thing is, that while accepted method is faster correct input (eg. '5') and slower for incorrect (eg. 'a'), my method is exact opposite (fast for incorrect and slower for correct).

    Still, in worst case, my method is 2 times faster than accepted solution for correct input and over 5 times faster for incorrect input.

提交回复
热议问题