JavaScript switch 語句是一種根據不同條件在代碼中做出判斷的方法。 它與使用多個 if-else 語句相比,它更具有組織性、代碼更簡潔。

switch 語句評估給定的表達式,它可以是變量或值,并將其與幾種可能的情況進行比較。
如果表達式的值與其中一種情況匹配,則執行關聯的代碼塊(一組指令)。 如果未找到匹配項,則可以執行可選的默認情況作為回退,這意味著它會在其他情況都不適用時運行。
例如,這是一個簡單的 switch 語句,它檢查名為 day 的變量的值:
switch (day) {
case "Monday":
console.log("Start of the work week! ??");
break;
case "Friday":
console.log("End of the work week! ??");
break;
default:
console.log("A regular day");
}
通過掌握 switch 語句,您可以編寫更干凈、更高效、組織更好的 JavaScript 代碼,最終提高您的整體編程技能。
switch 語句基礎:剖析和結構
switch 語句以關鍵字 switch 開頭,后跟括號中的表達式。 該表達式與包含在開關塊中的一系列 case 標簽進行比較。
每個 case 標簽代表一個不同的值,當表達式與 case 標簽的值匹配時,將執行 case 后面的代碼塊。
break 語句通常用于在執行匹配案例后退出 switch 塊,以確保僅運行預期的代碼塊,并防止跳轉到下一個案例。
可選地,可以包含默認案例以在沒有案例標簽匹配表達式時提供回退操作,確保對未知值的響應。
switch(expression) {
case {value1}:
// <-- Your Code to execute -->
break // optional
case {value2}:
// <-- Your Code to execute -->
break // optional
default: // optional
// <-- Code that executes when no values match-->
}
const superhero = 'Spider-Man';
switch (superhero) {
case 'Batman':
console.log('?? The Dark Knight!');
break;
case 'Wonder Woman':
console.log('?? The Amazon Princess!');
break;
default:
console.log('?? There are so many amazing superheroes!');
}
switch 與 if-else
當您有多個條件要處理時,switch 語句是比較好的處理方式,是使用多個 if-else 語句的替代方法。
if-else 語句適用于檢查一系列可以表示為 true 或 false 的條件,而 switch 語句在處理可以采用多個不同值的單個表達式時效率更高。
從本質上講,當您有多個相關條件需要管理時,switch 語句可以使您的代碼更清晰、更有條理且更易于閱讀。
例如,考慮以下 if-else 結構:
if (color === "red") {
console.log("The color is red ??");
} else if (color === "blue") {
console.log("The color is blue ??");
} else if (color === "green") {
console.log("The color is green ??");
} else {
console.log("Unknown color ??");
}
等效的 switch 語句如下所示:
switch (color) {
case "red":
console.log("The color is red ??");
break;
case "blue":
console.log("The color is blue ??");
break;
case "green":
console.log("The color is green ??");
break;
default:
console.log("Unknown color ??");
}
switch 語句提供了一種更有組織性和可讀性的方式來處理多種情況,尤其是在處理大量情況時。
在 switch 語句中,被計算的表達式是括號內的變量或值(在本例中為變量 color)。
何時使用 switch 與if-else
大量單變量條件:當您有大量條件要處理時,switch 語句通常比 if-else 鏈更有條理且更易于閱讀。
單變量評估:如果您正在評估的條件基于具有多個不同值的單個變量或表達式,則 switch 語句可以提供比 if-else 模式更高效、更簡潔的解決方案。
更快的代碼執行:在某些情況下,JavaScript 引擎可以優化 switch 語句,與一系列 if-else 語句相比,可以更快地執行代碼。
更容易維護:Switch 語句使添加、刪除或修改案例變得更容易,因為每個案例都獨立于 switch 塊中。 相比之下,if-else 鏈在需要更改時可能需要進行更廣泛的修改。
默認回退:Switch 語句提供了一個可選的默認情況,可以在沒有其他情況與給定表達式匹配時執行。 此功能允許以一種干凈的方式來處理意外或未知的值。
何時使用 if-else over switch
復雜條件:如果您正在評估的條件涉及復雜邏輯、多個變量或關系和邏輯運算符,則 if-else 模式提供了更大的靈活性,并且比 switch 語句更適合這些情況。
基于范圍的條件:當您需要檢查不是離散的值或條件的范圍時,if-else 模式提供了更好的解決方案,因為 switch 語句專為比較離散值而設計。
少量條件:如果您只有幾個簡單的條件要檢查,使用 if-else 模式比 switch 語句更直接、更容易編寫。
非常量情況:Switch 語句需要情況標簽的常量值,這意味著它們不能是在運行時更改的表達式。 如果您需要評估具有非常量值的條件,則 if-else 模式是合適的選擇。
評估真值或假值:當您需要檢查一個值是真值還是假值時,If-else 模式是合適的。Switch 語句不是為這種類型的評估而設計的,需要更冗長的代碼才能實現相同的結果。
提前退出條件:如果您有提前退出條件,一旦滿足某個條件就不需要進一步評估,if-else 模式會更有效。 使用 switch 語句,所有情況都會被評估,即使找到了早期匹配項(除非您使用“break”語句)。
決定 switch 或 if-else
switch 和 if-else 都解決了類似的問題,并且根據您的用例各有優缺點。 為了幫助您做出決定,我創建了一個簡單的 switch 語句:
switch (yourUseCase) {
case 'large_number_of_conditions':
case 'single_variable_evaluation':
case 'multiple_discrete_values':
console.log('Consider using a switch statement.');
break;
case 'complex_conditions':
case 'range_based_conditions':
case 'non_constant_cases':
console.log('Consider using an if-else pattern.');
break;
default:
console.log('Choose the most appropriate control structure based on your specific use case.');
}
switch 語句功能和技術:
switch 語句提供了額外的功能和概念,可用于提高代碼的性能、可讀性和簡潔性。
默認情況
當沒有其他情況與提供的表達式匹配時,將執行 switch 語句中的默認情況。 它作為處理意外值或未知值的回退,確保即使沒有匹配的情況也能提供響應。
const beverage = 'lemonade';
switch (beverage) {
case 'coffee':
console.log('?? Enjoy your coffee!');
break;
case 'tea':
console.log('?? Have a relaxing cup of tea!');
break;
default:
console.log('?? Your choice of drink is not listed, but cheers anyway!');
}
break關鍵字
break 關鍵字用在 switch 語句中,一旦找到并執行匹配的 case 就退出 switch 塊。 它阻止代碼繼續執行剩余的情況,確保只生成正確的輸出。
const transport = 'bike';
switch (transport) {
case 'car':
console.log('?? Drive safely!');
break;
case 'bike':
console.log('?? Enjoy your bike ride!');
break;
case 'bus':
console.log('?? Have a pleasant bus journey!');
break;
}
直通技術
一個 case 在 switch 語句中不能有多個條件。 要在一個案例中合并多個條件,請考慮使用 fall-through 技術。 它不僅可以節省您的時間,還可以確保您不會重蹈覆轍。
當您故意省略 case 中的 break 關鍵字時,會發生 switch 語句中的失敗,從而允許代碼執行繼續下一個 case,直到遇到 break 或到達 switch 塊的末尾。 當多個案例共享相同的輸出或操作時,這會很有用。
const clothing = 'jacket';
switch (clothing) {
case 't-shirt':
case 'shorts':
console.log('?? Looks like it\'s warm outside!');
break;
case 'jacket':
case 'sweater':
console.log('?? Bundle up, it\'s cold!');
// No break, fall-through to the next case
case 'scarf':
console.log('?? Don\'t forget your scarf!');
break;
}
常見問題和陷阱
多個案例執行(忘記使用 break 語句)
使用 switch 語句時的一個常見錯誤是沒有在每個 case 之后包含 break 語句。 此錯誤會導致意外失敗,執行多個案例而不是僅執行所需的案例。
如何修復它:在每個 case 之后添加一個 break 語句以防止 fall-through。
const mood = 'happy';
switch (mood) {
case 'happy':
console.log('?? Keep smiling!');
// <--- Missing break statement
case 'sad':
console.log('?? Cheer up!');
break;
case 'angry':
console.log('?? Take a deep breath!');
break;
}
// --Output--
//?? Keep smiling!
//?? Cheer up!
不正確的比較值和類型
Switch 語句使用嚴格比較,在比較不同數據類型時可能會導致意外結果。 在下面的示例中,字符串“2”不等于數字 2。這個陷阱可能會導致您的案例無法按預期執行。
如何修復:考慮變量的類型并記住它將被嚴格評估。 如果您正在處理較大的項目,TypeScript 可能會有所幫助。
const numOfPets = '2';
switch (numOfPets) {
case 2: // Because '2' !== 2
console.log('?? Double the fun!');
break;
default:
console.log('?? Share the love!');
}
// -- Output --
// ?? Share the love!
范圍問題
switch 語句中的一個常見缺陷是聲明沒有塊作用域或不正確作用域的變量,導致它們在其他情況下可訪問,或產生語法錯誤。 您可能會遇到 Uncaught SyntaxError: ... 如果您嘗試在多個子句中重新聲明相同的變量。
修復:
對于你打算在所有情況下使用的公共變量,在你的 switch 語句之前用 let 聲明它,或者;
將您的子句范圍限定為塊范圍(即用括號 { ... } 包裹您的子句)
阻止范圍你的條款:
// The problem:
switch (weather) {
case 'rain':
const notification = '??? ?Rainy days can be cozy!';
console.log(notification);
break;
case 'thunder':
// 'notification' is still accessible here
console.log(notification + ' ? Be careful!');
break;
}
// Fix 1: Use Block Scope when declaring
switch (weather) {
case 'rain': { // <-- look here.
const notification = '??? ?Rainy days can be cozy!';
console.log(notification);
break;
}
case 'thunder': {
const notification = '? Be careful!';
console.log(notification);
break;
}
}
// Fix 2: Declare it with let before your statement
let notification = '' // <-- look here.
switch (weather)
case 'rain':
notification = '??? ?Rainy days can be cozy!';
console.log(notification);
break;
case 'thunder':
notification = '? Be careful!';
console.log(notification);
break;
}
結論
既然您知道什么是 switch 語句、它是如何工作的以及何時使用它,是時候開始實現它了!