是否可能没有If/else条件。如果案件5不执行,我可以在那个地方做其他事吗?
号
switch语句将执行第一个匹配的情况下,再继续下去(忽略所有进一步的情况下标签),直到它获取到任何一个break语句或开关块的结束 - 但即使您可以通过省略break语句来“落后”到后续案例,交换机也不会提供任何机制来说“在此案例不匹配/执行时执行某些操作,还会继续尝试查找匹配案例”。
你所描述通常会用一系列if/else语句来完成:
var d=new Date(),
theDay=d.getDay(),
matched = false;
if (theDay===5) {
matched = true;
document.write("Finally Friday");
} else {
// your != 5 case here
}
if (theDay===6) {
matched = true;
document.write("Super Saturday");
} else {
// your != 6 case here
}
if (theDay===0) {
matched = true;
document.write("Sleepy Sunday");
} else {
// your != 0 case here
}
// default when none matched:
if (!matched) {
document.write("I'm looking forward to this weekend!");
}
请注意,我添加了一个matched
标记,以使默认工作。并且请注意,没有else if
语句,因为您需要执行每个if/else对。
如果你是真的决心用switch语句,你可以做一些傻类似如下:
var d=new Date(),
theDay=d.getDay(),
c,
cases = { // pre-list all the "not" cases
"!5" : true,
"!6" : true,
"!0" : true
};
// add case for theDay and remove the "not" case for theDay (if there is one)
cases[theDay] = true;
if (cases["!" + theDay])
delete cases["!" + theDay];
for (c in cases) {
switch(c) {
case "5":
document.write("Finally Friday");
break;
case "!5":
document.write("Finally Something");
break;
case "6":
document.write("Super Saturday");
break;
case "!6":
document.write("Finally Something - but not 6");
break;
case "0":
document.write("Sleepy Sunday");
break;
case "!0":
document.write("Finally Something - but not 0");
break;
default:
document.write("I'm looking forward to this weekend!");
}
}
如果你需要的情况下,按照特定的顺序来执行使用数组,而不是一个东西。
你的意思是要更改或添加到文本中'default'情况? – 2011-12-23 12:39:22
@FelixKling:我想如果5不执行,那么应该发生其他的事情... 6或0可能会执行... – 2011-12-23 12:40:09
使用普通老的if ... else有什么问题? – 2011-12-23 12:41:27