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

switch 語句評估給定的表達(dá)式,它可以是變量或值,并將其與幾種可能的情況進(jìn)行比較。
如果表達(dá)式的值與其中一種情況匹配,則執(zhí)行關(guān)聯(lián)的代碼塊(一組指令)。 如果未找到匹配項(xiàng),則可以執(zhí)行可選的默認(rèn)情況作為回退,這意味著它會在其他情況都不適用時運(yùn)行。
例如,這是一個簡單的 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 語句基礎(chǔ):剖析和結(jié)構(gòu)
switch 語句以關(guān)鍵字 switch 開頭,后跟括號中的表達(dá)式。 該表達(dá)式與包含在開關(guān)塊中的一系列 case 標(biāo)簽進(jìn)行比較。
每個 case 標(biāo)簽代表一個不同的值,當(dāng)表達(dá)式與 case 標(biāo)簽的值匹配時,將執(zhí)行 case 后面的代碼塊。
break 語句通常用于在執(zhí)行匹配案例后退出 switch 塊,以確保僅運(yùn)行預(yù)期的代碼塊,并防止跳轉(zhuǎn)到下一個案例。
可選地,可以包含默認(rèn)案例以在沒有案例標(biāo)簽匹配表達(dá)式時提供回退操作,確保對未知值的響應(yīng)。
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
當(dāng)您有多個條件要處理時,switch 語句是比較好的處理方式,是使用多個 if-else 語句的替代方法。
if-else 語句適用于檢查一系列可以表示為 true 或 false 的條件,而 switch 語句在處理可以采用多個不同值的單個表達(dá)式時效率更高。
從本質(zhì)上講,當(dāng)您有多個相關(guān)條件需要管理時,switch 語句可以使您的代碼更清晰、更有條理且更易于閱讀。
例如,考慮以下 if-else 結(jié)構(gòu):
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 語句中,被計算的表達(dá)式是括號內(nèi)的變量或值(在本例中為變量 color)。
何時使用 switch 與if-else
大量單變量條件:當(dāng)您有大量條件要處理時,switch 語句通常比 if-else 鏈更有條理且更易于閱讀。
單變量評估:如果您正在評估的條件基于具有多個不同值的單個變量或表達(dá)式,則 switch 語句可以提供比 if-else 模式更高效、更簡潔的解決方案。
更快的代碼執(zhí)行:在某些情況下,JavaScript 引擎可以優(yōu)化 switch 語句,與一系列 if-else 語句相比,可以更快地執(zhí)行代碼。
更容易維護(hù):Switch 語句使添加、刪除或修改案例變得更容易,因?yàn)槊總€案例都獨(dú)立于 switch 塊中。 相比之下,if-else 鏈在需要更改時可能需要進(jìn)行更廣泛的修改。
默認(rèn)回退:Switch 語句提供了一個可選的默認(rèn)情況,可以在沒有其他情況與給定表達(dá)式匹配時執(zhí)行。 此功能允許以一種干凈的方式來處理意外或未知的值。
何時使用 if-else over switch
復(fù)雜條件:如果您正在評估的條件涉及復(fù)雜邏輯、多個變量或關(guān)系和邏輯運(yùn)算符,則 if-else 模式提供了更大的靈活性,并且比 switch 語句更適合這些情況。
基于范圍的條件:當(dāng)您需要檢查不是離散的值或條件的范圍時,if-else 模式提供了更好的解決方案,因?yàn)?switch 語句專為比較離散值而設(shè)計。
少量條件:如果您只有幾個簡單的條件要檢查,使用 if-else 模式比 switch 語句更直接、更容易編寫。
非常量情況:Switch 語句需要情況標(biāo)簽的常量值,這意味著它們不能是在運(yùn)行時更改的表達(dá)式。 如果您需要評估具有非常量值的條件,則 if-else 模式是合適的選擇。
評估真值或假值:當(dāng)您需要檢查一個值是真值還是假值時,If-else 模式是合適的。Switch 語句不是為這種類型的評估而設(shè)計的,需要更冗長的代碼才能實(shí)現(xiàn)相同的結(jié)果。
提前退出條件:如果您有提前退出條件,一旦滿足某個條件就不需要進(jìn)一步評估,if-else 模式會更有效。 使用 switch 語句,所有情況都會被評估,即使找到了早期匹配項(xiàng)(除非您使用“break”語句)。
決定 switch 或 if-else
switch 和 if-else 都解決了類似的問題,并且根據(jù)您的用例各有優(yōu)缺點(diǎn)。 為了幫助您做出決定,我創(chuàng)建了一個簡單的 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 語句功能和技術(shù):
switch 語句提供了額外的功能和概念,可用于提高代碼的性能、可讀性和簡潔性。
默認(rèn)情況
當(dāng)沒有其他情況與提供的表達(dá)式匹配時,將執(zhí)行 switch 語句中的默認(rèn)情況。 它作為處理意外值或未知值的回退,確保即使沒有匹配的情況也能提供響應(yīng)。
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關(guān)鍵字
break 關(guān)鍵字用在 switch 語句中,一旦找到并執(zhí)行匹配的 case 就退出 switch 塊。 它阻止代碼繼續(xù)執(zhí)行剩余的情況,確保只生成正確的輸出。
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;
}
直通技術(shù)
一個 case 在 switch 語句中不能有多個條件。 要在一個案例中合并多個條件,請考慮使用 fall-through 技術(shù)。 它不僅可以節(jié)省您的時間,還可以確保您不會重蹈覆轍。
當(dāng)您故意省略 case 中的 break 關(guān)鍵字時,會發(fā)生 switch 語句中的失敗,從而允許代碼執(zhí)行繼續(xù)下一個 case,直到遇到 break 或到達(dá) switch 塊的末尾。 當(dāng)多個案例共享相同的輸出或操作時,這會很有用。
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;
}
常見問題和陷阱
多個案例執(zhí)行(忘記使用 break 語句)
使用 switch 語句時的一個常見錯誤是沒有在每個 case 之后包含 break 語句。 此錯誤會導(dǎo)致意外失敗,執(zhí)行多個案例而不是僅執(zhí)行所需的案例。
如何修復(fù)它:在每個 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 語句使用嚴(yán)格比較,在比較不同數(shù)據(jù)類型時可能會導(dǎo)致意外結(jié)果。 在下面的示例中,字符串“2”不等于數(shù)字 2。這個陷阱可能會導(dǎo)致您的案例無法按預(yù)期執(zhí)行。
如何修復(fù):考慮變量的類型并記住它將被嚴(yán)格評估。 如果您正在處理較大的項(xiàng)目,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 語句中的一個常見缺陷是聲明沒有塊作用域或不正確作用域的變量,導(dǎo)致它們在其他情況下可訪問,或產(chǎn)生語法錯誤。 您可能會遇到 Uncaught SyntaxError: ... 如果您嘗試在多個子句中重新聲明相同的變量。
修復(fù):
對于你打算在所有情況下使用的公共變量,在你的 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;
}
結(jié)論
既然您知道什么是 switch 語句、它是如何工作的以及何時使用它,是時候開始實(shí)現(xiàn)它了!