我需要在JavaScript开关语句的多个情况下,类似于:

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

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

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


当前回答

你可以这样写:

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

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

其他回答

你可以使用'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]()

如果你正在使用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');
}

注意,include在一些浏览器(包括旧版本的IE)中不能工作,但你可以很容易地修补它。有关更多信息,请参阅javascript中确定字符串是否在列表中的问题。

上述方法的问题在于,每次调用具有开关的函数时,都必须重复上述几种情况。更可靠的解决方案是使用地图或字典。

这里有一个例子:

// 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') }

下面是另一个易于使用的开关case语句。可以满足您的要求。我们可以在switch语句中使用find方法来获得所需的输出。

    switch(varname){
    case["afshin","saeed","larry"].find(name => name === varname):
        alert("Hey")
        break;
    default:
        alert('Default case');
        break;
}
<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>