Optimize OR in IF

前端 未结 7 824
不思量自难忘°
不思量自难忘° 2021-01-22 01:50

I have a code like this:

if (action == \'John\' || action == \'John Beckham\' || action == \'Henry John\'){
     alert(\'true!\');
}

How do I m

7条回答
  •  感情败类
    2021-01-22 02:35

    If "John" always appears, the simplest thing is:

    if (action.toLowerCase().indexOf("john") !== -1) {
        // Do something
    }
    

    ...but as your question has already changed the values against which you're checking action once, I hesitate to assume that. Also note that it will match "xxxjohnxxx", which may not be what you want.

    Original suggestions (updated for new action values from your edit):


    There are lots of ways, all shown using case insensitivity since you mentioned that in the comments:

    String#indexOf:

    if ("|john|john beckham|john henry|giggs john|scholes john|john messi|".indexOf("|" + action.toLowerCase() + "|") !== -1) {
        // Do something
    }
    

    Regular expressions:

    if (/^(?:John|John Beckham|John Henry|Giggs John|Scholes John|John Messi)$/i.test(action)) {
        // Do something
    }
    

    Because you're just using the true/false result, I'm using test which just returns true/false, instead of exec which returns matching results. Both work in this case, but the browser may be able to ever-so-slightly optimize test (but then, regex is unlikely to be the best solution if your goal is the fastest result or the least memory use).


    Or a switch:

    switch (action.toLowerCase()) {
        case "john":
        case "john beckham":
        case "john henry":
        case "giggs john":
        case "scholes john":
        case "john messi":
            // Do something
    }
    

    Or an object lookup:

    var actions = {
        "john":         true,
        "john beckham": true,
        "john henry":   true,
        "giggs john":   true,
        "scholes john": true,
        "john messi":   true
    };
    
    if (actions[action.toLowerCase()]) {
        // do something
    }
    

    (That also has the advantage of letting you say what to do — e.g., the true could be replaced with a function you call.)


    Or (on an ES5-enabled environment or with an ES5 shim) Array#indexOf:

    if (["john", "john beckham", "john henry", "giggs john", "scholes john", "john messi"].indexOf(action.toLowerCase()) !== -1 {
        // Do something
    }
    

    or since you use jQuery, you can avoid the shim on older browsers by using inArray:

    if ($.inArray(action.toLowerCase(), ["john", "john beckham", "john henry", "giggs john", "scholes john", "john messi"]) !== -1) {
        // Do something
    }
    

提交回复
热议问题