在做多條件時,我一般會盡量使用switch,但是判斷的條件需要表達式時,就只能灰溜溜的去使用if-elseif-else了。今天看到switch true,這種模式非常簡單,相信會是很好的體驗。
基本介紹
大多數JavaScript開發人員都熟悉switch語句(mdn docs),但是對於那些剛接觸該語言的人,讓我們簡要地介紹一下它。
switch語句使您可以將表達式與多種不同情況之一進行匹配:
const city = "London";
const getCountryByCity = () => {
switch (city) {
case "Edinburgh":
return "Edinburgh is the capital city of Scotland";
case "Madrid":
return "Madrid is the capital city of Spain";
case "London":
return "London is the capital city of England";
default:
return "Cannot find which country this city is the capital of.";
}
};
在這個例子中,表達式(城市變量)與switch語句中的每個case相匹配。如果案例與表達式的結果相匹配,案例將被執行--在這個例子中,它將返回一個字符串。
Switch (true)
switch true模式的基本原則是,你可以與表達式以及值相匹配。案例中的表達式將在匹配前被評估。如果你的案例中的表達式被評估爲 "真",它將被匹配。
switch (true) {
case 1 + 1 === 2:
// This case evaluates to true so it will be executed
default:
// This will not be executed
}
爲什麼這很有用
這種模式可以在許多不同的情況下使用--通常用來替代複雜的if/else語句。
一個常見的情況是,如果你正在驗證數據,並且有一組標準會導致驗證失敗,這種模式就會變得很方便。
const user = {
firstName: "Seán",
lastName: "Barry",
email: "[email protected]",
number: "00447123456789",
};
if (!user) {
throw new Error("User must be defined.");
} else if (!user.firstName) {
throw new Error("User's first name must be defined");
} else if (typeof user.firstName !== "string") {
throw new Error("User's first name must be a string");
} else if (// ... lots more validation here)
return user;
這可以用switch true這樣的方式重新編寫。
const user = {
firstName: "Seán",
lastName: "Barry",
email: "[email protected]",
number: "00447123456789",
};
switch (true) {
case !user:
throw new Error("User must be defined.");
case !user.firstName:
throw new Error("User's first name must be defined");
case typeof user.firstName !== "string":
throw new Error("User's first name must be a string");
default:
return user;
}
在寫if/else和switch true時,都可以抽象出驗證標準,以提高可讀性。
switch (true) {
case !isDefined(user):
throw new Error("User must be defined.");
case !isString(user.firstName):
throw new Error("User's first name must be a string");
case !isValidEmail(user.email):
throw new Error("User's email address must be a valid email address");
case !isValidPhoneNumber(user.number):
throw new Error("User's phone number must be a valid phone number");
// any number of other validation cases here
default:
return user;
}
總結
在我看來,這種模式在檢查多個條件時比大量的if/else塊提供了更清晰的可讀性。我相信這將會是一個很有爭議的問題,但是瞭解這些模式總是很有用的,這樣在適當的時候就可以使用它們。