Optimize OR in IF

前端 未结 7 809
不思量自难忘°
不思量自难忘° 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:47

    Try this, it uses indexOf:

    if (['a', 'b', 'c', 'd', 'e'].indexOf(action) > -1) {
      alert(true);
    }
    

    Update: If you want to support IE7 and below, use the answer to this question

    If you're using jQuery, you can use $.inArray like this:

    if ($.inArray(action, ['a','b','c','d') > -1) {
      alert(true);
    }
    

    UPDATE

    You can also use a regexp with test (The group makes the regexp not match "John Langhammerer" / actions with extra chars to the ones to be matched):

    if ((/^(John Langhammer|Piet Krauthammer|Some Guy)$/i).test(action)) {
      alert(true);
    }
    

    UPDATE: /i makes the regexp case insensitive.

    Below is a solution which would have worked for one-char actions:

    You can also use String.indexOf which is supported in IE7 (if your actions are all one char):

    if ('abcde'.indexOf(action) > -1) {
      alert(true);
    }
    

提交回复
热议问题