Switch statement multiple cases in JavaScript

I need multiple cases in switch statement in JavaScript, Something like:

switch (varName)
{
   case "afshin", "saeed", "larry": 
       alert('Hey');
       break;

   default: 
       alert('Default case');
       break;
}

How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows DRY concept.


Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:

switch (varName)
{
   case "afshin":
   case "saeed":
   case "larry": 
       alert('Hey');
       break;

   default: 
       alert('Default case');
}

This works in regular JavaScript

function theTest(val) {
  var answer = "";
  switch( val ) {
    case 1: case 2: case 3:
      answer = "Low";
      break;
    case 4: case 5: case 6:
      answer = "Mid";
      break;
    case 7: case 8: case 9:
      answer = "High";
      break;
    default:
      answer = "Massive or Tiny?";
  } 
  return answer;  
  }

  theTest(9);

Cheers.


这是完全避免switch语句的不同方法:

var cases = {
  afshin: function() { alert('hey'); },
  _default: function() { alert('default'); }
};
cases.larry = cases.saeed = cases.afshin;

cases[ varName ] ? cases[ varName ]() : cases._default();
链接地址: http://www.djcxy.com/p/4366.html

上一篇: 如何比较JavaScript中的数组?

下一篇: 在JavaScript中切换语句多个案例