7

At this moment I am using a switch case like this:

case 'something':
  // Do something
break;

What I would like to do is to have an array or strings like this:

case ['something', 'something too']:
  // Do something
break;

Is this possible to do?

If so how?

Κωλζαρ
  • 778
  • 1
  • 10
  • 21

4 Answers4

11

 var aStr = ['hello','something too','something'];
 for (var i = 0; i < aStr.length; i++){
   var supp = aStr[i];
   switch (supp) {
      case 'hello':
      case 'something': 
      case 'something too':
        // Do something
        console.log('Works!')
      break;
      default:
      break;
    }
  }

You can do like this.

Κωλζαρ
  • 778
  • 1
  • 10
  • 21
6

It can`t be done with switch construction, use if instead

if(array.includes('something' &&'something too')){
   return 'someData';
}
if(array.includes('something else')){
   return 'otherData';
}
Alexey Baguk
  • 182
  • 1
  • 6
4

This should work.

var arr = ['a', 'b'];

switch (arr.toString()) {
    case arr.toString():
        console.log('ok');
}
yuliskov
  • 1,312
  • 14
  • 15
0

Try This

 var my_array = ["A", "B", "C"];
     for(var i = 0; i<my_array.length;i++){
     switch(my_array[i]){
     case "A":
     console.log("It's A!");
     break;
     case "B":
     console.log("It's B!");
     break;
     case "C":
     console.log("It's C!");
     break;
     }
     }