3 回答
TA贡献1777条经验 获得超10个赞
好吧,原因之一就是清晰度。
如果您有开关/盒,则表达式无法更改....即
switch (foo[bar][baz]) {
case 'a':
...
break;
case 'b':
...
break;
}
而如果使用if / else,则如果您写错(或意图):
if (foo[bar][baz] == 'a') {
....
}
else if (foo[bar][baz+1] == 'b') {
....
}
人们在阅读您的代码时会怀疑“ foo表达式应该是相同的”还是“为什么它们不同”?
TA贡献1789条经验 获得超10个赞
还请记住,switch语句允许控制流继续进行,这允许您很好地组合条件,同时允许您为某些条件添加其他代码,例如以下代码:
switch (dayOfWeek)
{
case MONDAY:
garfieldUnhappy = true;
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
weekDay = true;
break;
case SATURDAY:
weekendJustStarted = true;
case SUNDAY:
weekendDay = true;
break;
}
if/else相反,在这里使用语句并不是那么好。
if (dayOfWeek == MONDAY)
{
garfieldUnhappy = true;
}
if (dayOfWeek == SATURDAY)
{
weekendJustStarted = true;
}
if (dayOfWeek == MONDAY || dayOfWeek == TUESDAY || dayOfWeek == WEDNESDAY
|| dayOfWeek == THURSDAY || dayOfWeek == FRIDAY)
{
weekDay = true;
}
else if (dayOfWeek == SATURDAY || dayOfWeek == SUNDAY)
{
weekendDay = true;
}
- 3 回答
- 0 关注
- 398 浏览
添加回答
举报