我需要在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概念的替代解决方案。
当前回答
我是这样使用的:
switch (true){
case /Pressure/.test(sensor):
{
console.log('Its pressure!');
break;
}
case /Temperature/.test(sensor):
{
console.log('Its temperature!');
break;
}
}
其他回答
只需改变开关条件方法:
switch (true) {
case (function(){ return true; })():
alert('true');
break;
case (function(){ return false; })():
alert('false');
break;
default:
alert('default');
}
我是这样使用的:
switch (true){
case /Pressure/.test(sensor):
{
console.log('Its pressure!');
break;
}
case /Temperature/.test(sensor):
{
console.log('Its temperature!');
break;
}
}
更干净的处理方法
if (["triangle", "circle", "rectangle"].indexOf(base.type) > -1)
{
//Do something
}else if (["areaMap", "irregular", "oval"].indexOf(base.type) > -1)
{
//Do another thing
}
您可以为具有相同结果的多个值执行此操作
<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>
使用switch语句的直通特性。匹配的case会一直运行,直到找到break(或者switch语句的结尾),所以你可以这样写:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
}