问题描述:

Is there such a way to compress a block of conditions in an if statement?

As you can see from the code, itemKey is a variable. I set the first letter to be lowercased so I can match it to another variable letter. The below works perfectly, but I would like to clean it up. Can I somehow pull all the || after the && together to encompass all number 0-9? This is acting as a string, not integer.

firstLetterLower = itemKey.charAt(0).toLowerCase();

if(firstLetterLower==letter || (

letter=='number' && (

firstLetterLower=='0' || firstLetterLower=='1' || firstLetterLower=='2' ||

firstLetterLower=='3' || firstLetterLower=='4' || firstLetterLower=='5' ||

firstLetterLower=='6' || firstLetterLower=='7' || firstLetterLower=='8' ||

firstLetterLower=='9'

))) {

网友答案:

Using a regex, you can do:

firstLetterLower = itemKey.charAt(0).toLowerCase();

if(firstLetterLower == letter || firstLetterLower.match(/^[0-9]$/) ){
}

This will check for your specified letter as well as match between 0 and 9.

However, if you don't want to use regex (overhead perhaps? Not that it would be noticeable here with 1 very simple regex), you can do as follows:

firstLetterLower = itemKey.charAt(0).toLowerCase();

if(firstLetterLower == letter || (firstLetterLower >= 0 && firstLetterLower <= 9)){
}
网友答案:

You can replace those tests with

firstLetterLower.match(/[0-9]/)

or

( firstLetterLower>=0 && firstLetterLower<=9 )
网友答案:

Try using a regex:

firstLetterLower.match(/^[0-9]/)
网友答案:

You can use a combination of regex and what you have. I would probably put it into a function:

function isMatch(itemKey, letter) {
    firstLetterLower = itemKey.charAt(0).toLowerCase();
    if (firstLetterLower == letter) return true;

    if (letter == 'number'){
       if (firstLetterLower.match(/[0-9]/))
         return true;
        }
     return false;
}


alert("1:" + isMatch('item', 'i'));
alert("2:" +isMatch('1234567', 'number'));
alert("3:" +isMatch('abc','number'));
alert("4:" +isMatch('123','a'));
相关阅读:
Top