2

So I've been using switch statements, and was wondering if there is a way to get several strings into one case, instead of only one string per case.

For example:

switch(fruits) {
case 'apples','bananas','oranges','strawberries':

//I'd like to get those four  fruits into one case, instead of doing this:   
switch (fruits) {
    case 'apples':
    break;
    case 'bananas':
    break;
    case 'oranges':
     break;
     case 'strawberries':

If this can be done it will save me a lot of time.

Edward K.
  • 173
  • 1
  • 2
  • 8
  • Possible duplicate of `http://stackoverflow.com/questions/13207927/switch-statement-multiple-cases-in-javascript` – VPK May 11 '15 at 11:11
  • 2
    `if (['apples','bananas','oranges','strawberries'].indexOf(fruits) >= 0 ...` – Alex K. May 11 '15 at 11:12
  • I looked through that post and it did not answer how to stuff everything into a single 'case' instead of having to type out 'case' multiple times (one case for each item) – Edward K. May 11 '15 at 11:14
  • wait are you testing a string that contains all 4 fruits? – Edwin Reynoso May 11 '15 at 11:18
  • Edwin, I was wanting to give one 'case' several fruits, instead of having to type them all out separately. Looks like that is not possible with a single 'case' and I was given some alternative answers below. – Edward K. May 11 '15 at 11:25

3 Answers3

2

Use it like:

switch (fruits) {
case 'apples':
case 'bananas':
case 'oranges': 
case 'strawberries': 
    //Your code
    break; 
}
Zee
  • 8,420
  • 5
  • 36
  • 58
  • That is still using multiple cases. How do I put all the fruits into only one case? – Edward K. May 11 '15 at 11:10
  • @EdwardK. [switch](http://www.w3schools.com/js/js_switch.asp) is not designed for that. And this will do what you want `//your code` will get executed if any of the above cases is true. – Zee May 11 '15 at 11:13
2

Do not use switch/case when you need multiple value matches. Use IF:

if(fruits === 'apples'  || 
   fruits === 'bananas' || 
   fruits === 'oranges' || 
   fruits === 'strawberries'){
   //do some action
}
freethinker
  • 2,257
  • 4
  • 26
  • 49
1

You could avoid the switch altogether: store all the fruits in an array and then use some to see if the fruit is there:

var arr = ['apples', 'bananas', 'oranges', 'strawberries'];

function check(arr, fruit) {
    return arr.some(function (el) {
        return el.indexOf(fruit) > -1;
    });
}

if (check(arr, 'oranges') {
    // do stuff if true
}

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95