案例1(抛出错误是没有开关案例匹配):
function getColorName(c) {
switch(c) {
case Color.Red:
return 'red, red wine';
case Color.Green:
return 'greenday';
case Color.Blue:
return "Im blue, daba dee daba";
default:
throw new Error('error');
}
}
getColorName(Color.Yellow);
案例2(默认情况下返回null,在调用者中处理):
function getColorName(c) {
switch(c) {
case Color.Red:
return 'red, red wine';
case Color.Green:
return 'greenday';
case Color.Blue:
return "Im blue, daba dee daba";
default:
return null;
}
}
if (getColorName(Color.Yellow)) {
}
这可能不是一个完美的例子。然而,
这个问题的目标是了解在存在切换逻辑的情况下,如何在避免过度复杂的同时覆盖尽可能多的用例?
虽然不在问题范围内,但作为澄清可能用例的一种手段,这种转换将通过以下方式实现
-
用一个
switch
(如上所述)
-
作为一个
if-elseif-else
功能(如果开关情况复杂或只有少数情况)
if-elseif else示例
(供参考):
function getColorName(c) {
if (Color.Red) {
return 'red, red wine';
}
else if (Color.Green) {
}
else {
return null;
}
}