995

我在 JavaScript 中的 switch 语句中需要多个案例,例如:

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

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

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

4

23 回答 23

2005

switch使用语句的贯穿功能。匹配的 case 将一直运行,直到找到 a break(或switch语句的结尾),所以你可以这样写:

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

   default: 
       alert('Default case');
}
于 2012-11-03T09:44:45.347 回答
136

这适用于常规 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);
于 2016-01-17T02:15:47.203 回答
49

这是完全避免该switch声明的不同方法:

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

cases[ varName ] ? cases[ varName ]() : cases._default();
于 2012-11-03T09:55:30.693 回答
27

在 Javascript 中,要在一个 switch 中分配多个 case,我们必须定义different case without break inbetween如下:

   <script>
      function checkHere(varName){
        switch (varName)
           {
           case "saeed":
           case "larry":
           case "afshin":
                alert('Hey');
                break;
          case "ss":
               alert('ss');
               break;
         default:
               alert('Default case');
               break;
       }
      }
     </script>

请看示例点击链接

于 2012-11-03T09:53:39.533 回答
22

为了清晰和DRY语法,我喜欢这个。

varName = "larry";

switch (true)
{
    case ["afshin", "saeed", "larry"].includes(varName) :
       alert('Hey');
       break;

    default:
       alert('Default case');

}
于 2020-02-04T00:16:57.083 回答
20

如果你使用 ES6,你可以这样做:

if (['afshin', 'saeed', 'larry'].includes(varName)) {
   alert('Hey');
} else {
   alert('Default case');
}

或者对于早期版本的 JavaScript,您可以这样做:

if (['afshin', 'saeed', 'larry'].indexOf(varName) !== -1) {
   alert('Hey');
} else {
   alert('Default case');
}

请注意,这在较旧的 IE 浏览器中不起作用,但您可以很容易地修补。有关更多信息,请参阅问题确定字符串是否在 javascript 中的列表中

于 2013-07-30T20:11:09.417 回答
15

我的情况类似于:

switch (text) {
  case SOME_CONSTANT || ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT || FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}

案件default总是进入。如果您遇到类似的多案例 switch 语句问题,您正在寻找这个:

switch (text) {
  case SOME_CONSTANT:
  case ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT:
  case FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}
于 2020-01-07T13:46:45.007 回答
9

添加和澄清Stefano 的答案,您可以使用表达式来动态设置 switch 中条件的值,例如:

var i = 3
switch (i) {
    case ((i>=0 && i<=5) ? i : -1):
        console.log('0-5');
        break;

    case 6: console.log('6');
}

因此,在您的问题中,您可以执行以下操作:

var varName = "afshin"
switch (varName) {
    case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
      console.log("hey");
      break;

    default:
      console.log('Default case');
}

虽然它是如此干燥......

于 2017-12-06T15:10:05.383 回答
8

在 Node.js 中,您似乎可以这样做:

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;
}

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

于 2015-09-01T09:12:30.363 回答
6

我这样使用它:

switch (true){
     case /Pressure/.test(sensor): 
     {
        console.log('Its pressure!');
        break;
     }

     case /Temperature/.test(sensor): 
     {
        console.log('Its temperature!');
        break;
     }
}
于 2018-02-21T12:40:49.600 回答
4

您可以使用“ in ”运算符...
它依赖于对象/哈希调用,因此它与 JavaScript 一样快。

// Assuming you have defined functions f(), g(a) and h(a,b)
// somewhere in your code,
// you can define them inside the object, but...
// the code becomes hard to read. I prefer it this way.

o = { f1:f, f2:g, f3:h };

// If you use "STATIC" code can do:
o['f3']( p1, p2 )

// If your code is someway "DYNAMIC", to prevent false invocations
// m brings the function/method to be invoked (f1, f2, f3)
// and you can rely on arguments[] to solve any parameter problems.
if ( m in o ) o[m]()
于 2014-09-06T12:51:28.440 回答
4

这取决于。 Switch评估一次且仅一次。在匹配时,无论 case 说什么,直到“break”的所有后续 case 语句都会触发。

var onlyMen = true;
var onlyWomen = false;
var onlyAdults = false;
 
 (function(){
   switch (true){
     case onlyMen:
       console.log ('onlymen');
     case onlyWomen:
       console.log ('onlyWomen');
     case onlyAdults:
       console.log ('onlyAdults');
       break;
     default:
       console.log('default');
   }
})(); // returns onlymen onlywomen onlyadults
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

于 2016-03-10T16:07:00.573 回答
3

一些有趣的方法。对我来说,最好的解决方法是使用.find.

您可以通过在 find 函数中使用合适的名称来指示多种情况。

switch (varName)
{
   case ["afshin", "saeed", "larry"].find(firstName => firstName === varName):
       alert('Hey');
       break;

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

其他答案更适合给定的示例,但是如果您对我有多种情况,这是最好的方法。

于 2021-06-25T10:30:23.260 回答
2

我可以看到这里有很多很好的答案,但是如果我们需要检查超过 10 个案例会发生什么?这是我自己的方法:

 function isAccessible(varName){
     let accessDenied = ['Liam', 'Noah', 'William', 'James', 'Logan', 'Benjamin',
                        'Mason', 'Elijah', 'Oliver', 'Jacob', 'Daniel', 'Lucas'];
      switch (varName) {
         case (accessDenied.includes(varName) ? varName : null):
             return 'Access Denied!';
         default:
           return 'Access Allowed.';
       }
    }

    console.log(isAccessible('Liam'));
于 2018-09-23T15:30:07.487 回答
2

上述方法的问题在于,case每次调用具有switch. 一个更强大的解决方案是拥有一个地图字典

这是一个例子:

// The Map, divided by concepts
var dictionary = {
  timePeriod: {
    'month': [1, 'monthly', 'mensal', 'mês'],
    'twoMonths': [2, 'two months', '2 months', 'bimestral', 'bimestre'],
    'trimester': [3, 'trimesterly', 'quarterly', 'trimestral'],
    'semester': [4, 'semesterly', 'semestral', 'halfyearly'],
    'year': [5, 'yearly', 'annual', 'ano']
  },
  distance: {
    'km': [1, 'kms', 'kilometre', 'kilometers', 'kilometres'],
    'mile': [2, 'mi', 'miles'],
    'nordicMile': [3, 'Nordic mile', 'mil (10 km)', 'Scandinavian mile']
  },
  fuelAmount: {
    'ltr': [1, 'l', 'litre', 'Litre', 'liter', 'Liter'],
    'gal (imp)': [2, 'imp gallon', 'imperial gal', 'gal (UK)'],
    'gal (US)': [3, 'US gallon', 'US gal'],
    'kWh': [4, 'KWH']
  }
};

// This function maps every input to a certain defined value
function mapUnit (concept, value) {
  for (var key in dictionary[concept]) {
    if (key === value ||
      dictionary[concept][key].indexOf(value) !== -1) {
      return key
    }
  }
  throw Error('Uknown "'+value+'" for "'+concept+'"')
}

// You would use it simply like this
mapUnit("fuelAmount", "ltr") // => ltr
mapUnit("fuelAmount", "US gal") // => gal (US)
mapUnit("fuelAmount", 3) // => gal (US)
mapUnit("distance", "kilometre") // => km

// Now you can use the switch statement safely without the need
// to repeat the combinations every time you call the switch
var foo = 'monthly'
switch (mapUnit ('timePeriod', foo)) {
  case 'month':
    console.log('month')
    break
  case 'twoMonths':
    console.log('twoMonths')
    break
  case 'trimester':
    console.log('trimester')
    break
  case 'semester':
    console.log('semester')
    break
  case 'year':
    console.log('year')
    break
  default:
    throw Error('error')
}

于 2019-02-25T14:28:04.180 回答
2

你可以这样做:

alert([
  "afshin", 
  "saeed", 
  "larry",
  "sasha",
  "boby",
  "jhon",
  "anna",
  // ...
].includes(varName)? 'Hey' : 'Default case')

或者只是一行代码:

alert(["afshin", "saeed", "larry",...].includes(varName)? 'Hey' : 'Default case')

埃里克的回答有一点改进

于 2019-05-06T00:33:41.747 回答
1

一种可能的解决方案是:

const names = {
afshin: 'afshin',
saeed: 'saeed',
larry: 'larry'
};

switch (varName) {
   case names[varName]: {
       alert('Hey');
       break;
   }

   default: {
       alert('Default case');
       break;
   }
}
于 2019-07-11T14:54:50.773 回答
-1

在函数内部时,在switch语句中执行多个案例的另一种方法:

function name(varName){
  switch (varName) {
     case 'afshin':
     case 'saeed':
     case 'larry':
       return 'Hey';
     default:
       return 'Default case';
   }
}

console.log(name('afshin')); // Hey

于 2018-01-09T22:37:46.843 回答
-1

更清洁的处理方式

if (["triangle", "circle", "rectangle"].indexOf(base.type) > -1)
{
    //Do something
}else if (["areaMap", "irregular", "oval"].indexOf(base.type) > -1)
{
    //Do another thing
}

您可以对具有相同结果的多个值执行此操作

于 2021-09-07T13:17:32.943 回答
-2

只需更改开关条件方法:

switch (true) {
    case (function(){ return true; })():
        alert('true');
        break;
    case (function(){ return false; })():
        alert('false');
        break;
    default:
        alert('default');
}
于 2015-12-16T10:02:56.583 回答
-4
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Example1</title>
    <link rel="stylesheet" href="css/style.css" >
    <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
    <script>
        function display_case(){
            var num =   document.getElementById('number').value;

                switch(num){

                    case (num = "1"):
                    document.getElementById("result").innerHTML = "You select day Sunday";
                    break;

                    case (num = "2"):
                    document.getElementById("result").innerHTML = "You select day  Monday";
                    break;

                    case (num = "3"):
                    document.getElementById("result").innerHTML = "You select day  Tuesday";
                    break;

                    case (num = "4"):
                    document.getElementById("result").innerHTML = "You select day  Wednesday";
                    break;

                    case (num = "5"):
                    document.getElementById("result").innerHTML = "You select day  Thusday";
                    break;

                    case (num = "6"):
                    document.getElementById("result").innerHTML = "You select day  Friday";
                    break;

                    case (num = "7"):
                    document.getElementById("result").innerHTML = "You select day  Saturday";
                    break;

                    default:
                    document.getElementById("result").innerHTML = "You select day  Invalid Weekday";
                    break
                }

        }
    </script>
</head>
<body>
    <center>
        <div id="error"></div>
        <center>
            <h2> Switch Case Example </h2>
            <p>Enter a Number Between 1 to 7</p>
            <input type="text" id="number" />
            <button onclick="display_case();">Check</button><br />
            <div id="result"><b></b></div>
        </center>
    </center>
</body>
于 2015-10-05T09:07:09.233 回答
-4

你可以这样写:

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

   default: 
       alert('Default case');
       break;
}         
于 2016-02-24T11:37:49.970 回答
-6

对我来说这是最简单的方法:

switch (["afshin","saeed","larry"].includes(varName) ? 1 : 2) {
   case 1:
       alert('Hey');
       break;

   default:
       alert('Default case');
       break;
}
于 2019-11-21T07:29:52.687 回答