我需要在JavaScript开关语句的多个情况下,类似于:
switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
我该怎么做呢?如果在JavaScript中没有办法做这样的事情,我想知道一个也遵循DRY概念的替代解决方案。
我需要在JavaScript开关语句的多个情况下,类似于:
switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
我该怎么做呢?如果在JavaScript中没有办法做这样的事情,我想知道一个也遵循DRY概念的替代解决方案。
当前回答
添加并澄清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');
}
虽然很干…
其他回答
对我来说,这是最简单的方法:
switch (["afshin","saeed","larry"].includes(varName) ? 1 : 2) {
case 1:
alert('Hey');
break;
default:
alert('Default case');
break;
}
上述方法的问题在于,每次调用具有开关的函数时,都必须重复上述几种情况。更可靠的解决方案是使用地图或字典。
这里有一个例子:
// 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') }
添加并澄清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');
}
虽然很干…
这在常规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);
视情况而定。Switch计算一次且仅计算一次。在匹配时,所有后续的case语句直到“break”火,无论case说什么。
var onlyMen = true; var onlyWomen = false; var only成人= false; (函数(){ 开关(真){ 案例onlyMen: console.log(“onlymen”); 案例onlyWomen: console.log(“onlyWomen”); 案例onlyAdults: console.log(“onlyAdults”); 打破; 默认值: console.log(“违约”); } }) ();//只返回男人,只返回女人,只返回成年人 < script src = " https://getfirebug.com/firebug-lite-debug.js " > < /脚本>