是否可能沒有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