www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: javascript switch with multiple values in case

  1. #1
    Join Date
    Jul 2006
    Posts
    146

    javascript switch with multiple values in case

    I would like to do a switch in javascript, with multiple values in the case.

    So, would like

    Code:
    switch (varName)
    {
       case "mike","joe","larry": alert('cool');
       break;
    
      default: alert('also cool');
      break;
    }
    
    is this possible ?    (thanks for answers.)
    
    
    }

  2. #2
    Join Date
    Sep 2008
    Location
    Canada
    Posts
    246
    Hi,

    In short, no. The case statement adheres to a strict template

    For more info, you can try messing around on the example at http://www.w3schools.com/js/js_switch.asp .

  3. #3
    Join Date
    Jul 2006
    Posts
    146
    Thanks for the response.

    I put together a solution using if conditional statments (inside a switch statement, in the default case.) Not as nice as i would like, but it should work.

    Thanks for the clarification.

    MP

  4. #4
    Join Date
    Sep 2008
    Location
    Canada
    Posts
    246
    Ok I lied.

    Code:
    switch (varName)
    {
       case "mike": case "joe": case "larry": 
       alert('cool');
       break;
    
      default: 
      alert('also cool');
      break;
    }
    Try that out.

  5. #5
    Join Date
    Sep 2006
    Location
    Copenhagen, Denmark
    Posts
    1,253
    JS is diffrent from other languages like C when it comes to switches. If you are using a fall through switch like suggested above you should see this thread for a detailed explanation.

    In general try to avoid fall through switch statements as it will make your code harder to understand.

  6. #6
    Join Date
    Mar 2005
    Location
    Sydney, Australia
    Posts
    7,974
    A fallthrough switch where the case labels directly follow one another is clear enough to read particularly if you put them all on the one line. It is ones that contain code between the case labels and still fall through that can be confusing (and should therefore be commented if you use them so as to make it clear that the break is deliberately omitted).

  7. #7
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    What is the final scope, after all? You may use rather a while or a for loop instead of a switch...

  8. #8
    Join Date
    Oct 2010
    Posts
    1

    How about this

    Why not just use the same comparison operator that you would use in an IF statement?

    Code:
    switch (varName)
    {
       case "mike" || "joe" || "larry": 
            alert('cool');
       break;
    
      default: 
           alert('also cool');
      break;
    }
    This way, the code is easier to read (IMO) and much cleaner (again - IMO).

  9. #9
    Join Date
    Jun 2007
    Posts
    667
    Quote Originally Posted by eljaywilson View Post
    Why not just use the same comparison operator that you would use in an IF statement?

    Code:
    switch (varName)
    {
       case "mike" || "joe" || "larry": 
            alert('cool');
       break;
    
      default: 
           alert('also cool');
      break;
    }
    If you do that, only the first value is considered.

  10. #10
    Join Date
    Apr 2011
    Posts
    1
    I would usually not revive a dead thread, but this is the #1 result on google for "javascript switch case", which I happened to have looked for. As such, I figure since nobody had actually answered the question, I'd pop in and offer the correct solution.

    Don't use "break;" at the end of the first comparisons. Ie:
    Code:
    switch( varName) {
      case "mike" :
      case "joe" :
      case "larry" : alert('cool'); break;
      default : alert('also cool');   // No need for a break; here
    }
    mike, joe, and larry will all give the alert message of 'cool'.

  11. #11
    Join Date
    Aug 2007
    Posts
    3,767
    And while we're digging up old threads, I might as well clarify the point. Once a case has evaulated to true, all statements after that case will be evaluated until the end of the switch statement, or until it is terminated. Once a case is true, that's it. No more cases are checked, just all the statements executed until the end or the switch is terminated. The only way I know to do the latter is with break. This is the behaviour of switch in all languages I know, particularly C, unlike what Dok sort of implies.

  12. #12
    Join Date
    May 2011
    Posts
    3

    switch multiple

    Bit of a hack below... Like many others, I discovered this thread looking for a simple way to do multiple cases, and although correct answer was found above, I still had an unsatisfied desire to get case functionality without all that extra 'case' keyword repetition.

    Below is my attempt at hacking a switch-cases data structure that can handle arrays as it's case values.

    I believe the behavior is true to the original switch statement. I haven't done performance testing on it, and it's probably a lot slower than a native switch. Still, if you need the functionality, this may be cleaner, or at least easier to maintain. An interesting benefit is this version also allows for negative case handling.

    PHP Code:
    var val2;
    var 
    d=document;
    var 
    action;

    //whole thing wrapped in do-while to allow for 'break' functionality.
    do{

         
    switchArrayCase(val,[0,2,4,6,7,9,11]) ? d.write('31 days') : /*do nothing*/;  
                          break;

         
    switchArrayCase(val,[3,5,8,10]) ? d.write('30 days') : /*do nothing*/;  
                          break;

         
    switchArrayCase(val,[1]) ? d.write('28 days unless leap-year') : /*do nothing*/;
                          break;
         
    //default
         
    d.write('not a month');

    //only runs once because 'while' is set to 'false'.
    } while(false);


    function 
    switchArrayCase(item,array)
    {
          var 
    alen=array.length;
          while (
    alen--)
          {
                if(array[
    alen]==item){return true;}
          }
          return 
    false;


  13. #13
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787

    using objects instead of switch

    as long as you just need "one of the above" choices on strings or numbers, it's MUCH faster to use objects for making decision trees.
    besides, the code given blueTeam only checks the first conditional, stopping at the first break. it's also confusing to use a ternary in conjunction with a empty statement.



    PHP Code:
    var val2;
    var 
    d=document;
    var 
    action;

    //whole thing wrapped in do-while to allow for 'break' functionality.
    do{

        if({
    0:1,2:1,4:2,6:1,7:1,9:1,11:1}[val]){d.write('31 days'); break;}
        if({
    3:1,5:1,8:210:1}[val]){ d.write('30 days');  break;}
        if({
    1:1}[val]){ d.write('28 days unless leap-year'); break;}

         
    //default
         
    d.write('not a month');

    //only runs once because 'while' is set to 'false'.
    } while(false); 



    if you had more choices to make, often you can simply assign a variable as the correct property of an object, without any loops or structure code.
    since the example provided uses numbers, it's even simpler than using an object: we can use an array to make a comma-separated list of value conversions:
    PHP Code:
    var val2;
    var 
    d=document;
    var 
    action;
    var 
    months=[31,28,31,30,31,30,31,31,30,31,30,31];
    d.write
      
    months[val] || 'not a month'
    ); 

    if you were in love with " days", you do need one decision operation:

    PHP Code:
    var val2;
    var 
    d=document;
    var 
    action;
    var 
    months=[31,28,31,30,31,30,31,31,30,31,30,31];
    d.write
      
    months[val] ? (months[val]+" days") : 'not a month'
    ); 
    much simpler than special functions and much faster than nested loops.

  14. #14
    Join Date
    May 2011
    Posts
    3
    Whoops, probably should have tested that before posting...

    Thanks for the optimizations rnd_me.
    I'd never thought to use a virtual object like that.

    My goal was to be able to select from a random set of available values, so, thanks to your help, I think something like this will do the trick:

    PHP Code:
    var val=2;

    var 
    optionsA = {0:['a','b','c'],2:['d','e','f']}[val];
    var 
    optionsB = {1:['g','h','i'],3:['j','k','l']}[val];
    do{
    if(
    optionsA){alert('you get:'+optionsA[Math.floor(Math.random()*optionsA.length) ]); break;} 
    if(
    optionsB){alert('you get:'+optionsB[Math.floor(Math.random()*optionsB.length)  ]); break;} 
    } while(
    false); 
    Any suggestions for further optimization?

  15. #15
    Join Date
    May 2011
    Posts
    3
    Or, rather...

    PHP Code:
    var val=2;

    var 
    optionsA = {0:['a','b','c'],2:['d','e','f']}[val];
    var 
    optionsB = {1:['g','h','i'],3:['j','k','l']}[val];
    do{
    if(
    optionsA){alert('A gets:'+optionsA[Math.floor(Math.random()*optionsA.length) ]); break;} 
    if(
    optionsB){alert('B gets:'+optionsA[Math.floor(Math.random()*optionsA.length)  ]); break;} 
    } while(
    false); 
    The previous example didn't distinguish output between A and B... (which I needed)

    thanks again.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles