How to do this if the statement is shorter?

Can I make this statement shorter?

if(abc=='value1' || abc=='value2' || abc=='value3') {//do something}

so that it looks something like this:

if(abc=='value1' || 'value2' || 'value3'){//do something}

Thank.

0
source share
6 answers

You have several options:

  • Leave it as it is;
  • Use associative array / object;
  • Use switch.

The second form is invalid. Javascript Syntax

(2) something like:

var abcOptions = {
  "value1" : true,
  "value2" : true,
  "value3" : true
};
if (abcOptions[abc]) {
  ...
}

(3):

switch (abc) {
  case "value1":
    ...
    break;
  case "value2":
    ...
    break;
  case "value3":
    ...
    break;
}

Personally, I am not a big fan of this in terms of readability, but it is a sensible approach with a lot of meanings.

I do not necessarily recommend this, but it may be an option in certain circumstances. If you are dealing with only three values, use:

if (abc == "value1" || abc == "value2" || abc == "value3") {
  ...
}

since it is much more readable.

+9
if (['value1', 'value2', 'value3'].indexOf(abc) != -1)

, , .

+2

You can use the switch:

switch (abc) { case 'value1': case 'value2': case 'value3': {
  // do something
}}

Or written in a more traditional form:

switch (abc) {
  case 'value1':
  case 'value2':
  case 'value3': {
    // do something
  }
}
+1
source
if(abc.match(/^value[1-3]$/)) {
    //doSomething....
}
+1
source
if ( abc.search(/value[123]/) != -1 ) ...do your stuff ...
0
source

You can use the operator switch. Like this:

switch(abc) {
    'value1':
    'value2':
    'value3':
         // do something
         break;
    default:
         // noop
}

But your original ifwith ||is probably still preferable.

0
source

All Articles