Javascript 如何在switch语句中使用多个case
我在一个与我类似的问题中找到了这个答案,但我仍然有疑问 使用switch语句的fall-through功能。对案 将一直运行,直到找到中断(或switch语句的结尾), 所以你可以这样写:Javascript 如何在switch语句中使用多个case,javascript,Javascript,我在一个与我类似的问题中找到了这个答案,但我仍然有疑问 使用switch语句的fall-through功能。对案 将一直运行,直到找到中断(或switch语句的结尾), 所以你可以这样写: switch (varName) { case "afshin": case "saeed": case "larry": alert('Hey'); break; default: alert('Default ca
switch (varName) {
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
}
这意味着“如果varName是afshin&&saeed&&larry”,或者它意味着“如果varName是afshin | | saeed | larry”
提前谢谢 正如前面的回答所说 匹配的案例将一直运行,直到找到中断(或switch语句的结尾) <> >为了更好地理解这是如何工作的,请考虑这个例子:
switch (varName) {
case "afshin":
alert("afshin");
case "saeed":
alert("saeed");
case "larry":
alert('larry');
break;
default:
alert('Default case');
}
因为只有“拉里”案有机会
如果varName==“afshin”,您将收到3个警报(“afshin”、“saeed”、“larry”)
如果varName==“saeed”,您将收到2个警报(“saeed”、“larry”)
如果varName==“larry”,您将得到1个警报(“larry”)
这就是为什么打破所有案例非常重要的原因,除非你绝对想让案例陈述进入下一个案例
长话短说,写作:
case "afshin":
case "saeed":
case "larry":
alert("hi");
break;
相当于
if(varName == "afshin" || varName == "saeed" || varName == "larry"){
alert("hi");
}
afshin | | saeed | | | larry变量怎么可以同时是三个不同的字符串?记住,当您以非惯用的方式处理案例时,始终要进行注释。在switch语句中不加分隔符可能会导致模糊错误。@Pointy Your right…抱歉,我是编程新手;)