我需要在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概念的替代解决方案。
当前回答
上述方法的问题在于,每次调用具有开关的函数时,都必须重复上述几种情况。更可靠的解决方案是使用地图或字典。
这里有一个例子:
// 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') }
其他回答
我喜欢它的清晰度和DRY语法。
varName = "larry";
switch (true)
{
case ["afshin", "saeed", "larry"].includes(varName) :
alert('Hey');
break;
default:
alert('Default case');
}
在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;
}
这使得代码在某些情况下更加紧凑。
下面是另一个易于使用的开关case语句。可以满足您的要求。我们可以在switch语句中使用find方法来获得所需的输出。
switch(varname){
case["afshin","saeed","larry"].find(name => name === varname):
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') }
我的情况类似于:
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');
}
总是输入默认大小写。如果你遇到了类似的多例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');
}