在JavaScript中切换语句多个案例

我需要在JavaScript的switch语句中使用多种情况,例如:

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

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

我怎样才能做到这一点?如果没有办法在JavaScript中执行类似的操作,我想知道一个也遵循DRY概念的替代解决方案

小小TomNear2020/03/11 12:02:08

在节点中,似乎可以执行此操作:

data = "10";
switch(data){
case "1": case "2": case "3": //put multiple cases on the same line to save vertical space.
   console.log("small"); break;
case "10": case "11": case "12":
   console.log("large"); break;
default:
   console.log("strange");
   break;
}

在某些情况下,这使代码更紧凑。

Gil梅2020/03/11 12:02:08

这适用于常规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);

干杯。