Check if character is number?

前端 未结 22 753
误落风尘
误落风尘 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:51

    I think it's very fun to come up with ways to solve this. Below are some.
    (All functions below assume argument is a single character. Change to n[0] to enforce it)

    Method 1:

    function isCharDigit(n){
      return !!n.trim() && n > -1;
    }
    

    Method 2:

    function isCharDigit(n){
      return !!n.trim() && n*0==0;
    }
    

    Method 3:

    function isCharDigit(n){
      return !!n.trim() && !!Number(n+.1); // "+.1' to make it work with "." and "0" Chars
    }
    

    Method 4:

    var isCharDigit = (function(){
      var a = [1,1,1,1,1,1,1,1,1,1];
      return function(n){
        return !!a[n] // check if `a` Array has anything in index 'n'. Cast result to boolean
      }
    })();
    

    Method 5:

    function isCharDigit(n){
      return !!n.trim() && !isNaN(+n);
    }
    

    Test string:

    var str = ' 90ABcd#?:.+', char;
    for( char of str ) 
      console.log( char, isCharDigit(char) );
    

提交回复
热议问题