Switch statement multiple cases in JavaScript
我需要在javascript中的switch语句中使用多个案例,比如:
1 2 3 4 5 6 7 8 9 10 | switch (varName) { case"afshin","saeed","larry": alert('Hey'); break; default: alert('Default case'); break; } |
我该怎么做?如果在JavaScript中没有办法做到这一点,那么我想知道一个也遵循Dry概念的替代解决方案。
使用
1 2 3 4 5 6 7 8 9 10 11 | switch (varName) { case"afshin": case"saeed": case"larry": alert('Hey'); break; default: alert('Default case'); } |
这在常规的javascript中工作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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); |
干杯。
以下是避免
1 2 3 4 5 6 7 | var cases = { afshin: function() { alert('hey'); }, _default: function() { alert('default'); } }; cases.larry = cases.saeed = cases.afshin; cases[ varName ] ? cases[ varName ]() : cases._default(); |
在JS中,为了在交换机中分配多个案例,我们必须定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function checkHere(varName){ switch (varName) { case"saeed": case"larry": case"afshin": alert('Hey'); break; case"ss": alert('ss'); break; default: alert('Default case'); break; } } |
请参阅示例单击链接
如果您使用ES6,可以这样做:
1 2 3 4 5 | if (['afshin', 'saeed', 'larry'].includes(varName)) { alert('Hey'); } else { alert('Default case'); } |
或者对于早期版本的javascript,您可以这样做:
1 2 3 4 5 | if (['afshin', 'saeed', 'larry'].indexOf(varName) !== -1) { alert('Hey'); } else { alert('Default case'); } |
请注意,这在旧的IE浏览器中不起作用,但您可以很容易地对其进行修补。有关详细信息,请参阅问题"确定字符串是否在javascript的列表中"。
添加和澄清Stefano的答案时,可以使用表达式以常规方式设置开关中条件的值,例如:
1 2 3 4 5 | var i = 3 switch (i) { case ((i>=0 && i<=5)?i:-1): console.log('0-5'); break; case 6: console.log('6'); } |
所以在你的问题中,你可以做一些类似的事情:
1 2 3 4 5 6 7 8 9 | var varName ="afshin" switch (varName) { case (["afshin","saeed","larry"].indexOf(varName)+1 && varName): console.log("hey"); break; default: console.log('Default case'); } |
虽然没有那么干……
您可以使用"in"运算符…依赖于对象/哈希调用…所以它的速度和javascript一样快…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // 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 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]() |
享受,Zee
我这样使用:
1 2 3 4 5 6 7 8 9 10 | switch (true){ case /Pressure/.test(sensor):{ console.log('Its pressure!'); break; } case /Temperature/.test(sensor):{ console.log('Its temperature!'); break; } } |
这要看情况而定。开关只计算一次。在匹配时,所有随后的案例陈述,直到"中断"触发,不管案例说什么。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
1 | <script src="https://getfirebug.com/firebug-lite-debug.js"> |
在节点中,似乎允许您执行此操作:
1 2 3 4 5 6 7 8 9 10 | 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; } |
在某些情况下,这使得代码更加紧凑。
我可以看到这里有很多很好的答案,但是如果我们需要检查10个以上的病例会发生什么?以下是我自己的方法:
1 2 3 4 5 6 7 8 9 10 11 12 | 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')); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | switch (myVariable) { case"A": case"B": case"C": // Do something break; case"D": case"E": // Do something else break; default: // Default case break; } |
在本例中,如果myvariable的值是a、b或c,它将在case"c":下执行代码。
上述方法的问题是,每次调用具有
这里举个例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | // the Map, divided by concepts var dictionary = { timePeriod: { 'month': [1, 'monthly', 'mensal', 'mês'], 'twoMonths': [2, 'two months', '2 motnhs', 'bimestral', 'bimestre'], 'trimester': [3, 'trimesterly', 'quarterly', 'trimestral'], 'semester': [4, 'semesterly', 'semestral', 'halfyearly'], 'year': [5, 'yearly', 'anual', 'ano'] }, distance: { 'km': [1, 'kms', 'kilometre', 'kilometers', 'kilometres'], 'mile': [2, 'mi', 'miles'], 'nordicMile': [3, 'nordic mile', 'mil(10km)', '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') } |
1 | <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> |
在switch语句中执行多个事例的另一种方法(在函数内部时)
1 2 3 4 5 6 7 8 9 10 11 12 | function name(varName){ switch (varName) { case 'afshin': case 'saeed': case 'larry': return 'Hey'; default: return 'Default case'; } } console.log(name('afshin')); //Hey |
你可以这样写:
1 2 3 4 5 6 7 8 9 10 11 12 | switch (varName) { case"afshin": case"saeed": case"larry": alert('Hey'); break; default: alert('Default case'); break; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> Example1 <link rel="stylesheet" href="css/style.css"> <script src="js/jquery-1.11.3.min.js" type="text/javascript"> 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 } } </head> <body> <center> <center> Switch Case Example <p> Enter a Number Between 1 to 7 </p> <input type="text" id="number" /> <button onclick="display_case();">Check</button><br /> </center> </center> </body> |
只需按箭头所示切换开关状态即可。
1 2 3 4 5 6 7 8 9 10 | switch (true) { case (function(){ return true; })(): alert('true'); break; case (function(){ return false; })(): alert('false'); break; default: alert('default'); } |