JavaScript Switch 语句
JavaScript switch 语句
Section titled “JavaScript switch 语句”The switch statement is a control flow statement used to execute different blocks of code based on the value of an expression. It’s often an alternative to a long if...else if...else chain when dealing with multiple discrete values.
理解 switch 语句
Section titled “理解 switch 语句”The switch statement evaluates an expression once and compares its value against a series of case clauses. If a match is found, the code block associated with that case is executed.
switch (expression) { case value1: // 如果 expression === value1,则执行此代码块 break; // 重要:阻止执行穿透到下一个 case case value2: // 如果 expression === value2,则执行此代码块 break; // … 更多 case default: // 如果没有 case 匹配,则执行此代码块 // (可选,但建议使用) }
工作原理:
- 对
expression求值一次。 - 使用严格相等 (
===) 将expression的值与每个case中的值进行比较。 - 如果找到匹配项,则从该
case开始的代码块将被执行。 break关键字至关重要。如果省略,执行将“穿透”(fall through)到下一个case块,无论其值是否匹配。这有时是故意的,但如果不小心遗漏,通常会导致 bug。default子句是可选的。如果没有case与表达式的值匹配,则执行它。建议包含一个defaultcase,即使它只是用来记录一个意外的值。
示例:获取星期几。
let dayName;const dayNumber = new Date().getDay(); // 0 代表星期日,1 代表星期一,...,6 代表星期六
switch (dayNumber) { case 0: dayName = "Sunday"; break; case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; default: dayName = "Invalid day number"; // 使用 getDay() 不会发生这种情况}
console.log(`Today is ${dayName}.`);The break Keyword
Section titled “The break Keyword”When the JavaScript interpreter reaches a break keyword inside a switch block, it exits the switch statement entirely. Execution continues with the statement immediately following the switch block.
If break is omitted, execution continues into the next case block. This is called “fall-through” and can sometimes be used intentionally, but it’s a common source of errors if forgotten.
示例:穿透(有意为之)。
const fruit = "apple";let type;
switch (fruit) { case "apple": case "pear": case "banana": type = "Common fruit"; break; // 在此退出 switch case "orange": case "lemon": type = "Citrus fruit"; break; default: type = "Unknown fruit";}console.log(`${fruit} is a ${type}.`); // 输出: apple is a Common fruit.The default Keyword
Section titled “The default Keyword”The default keyword specifies the block of code to run if no case value matches the switch expression. It’s similar to the else clause in an if...else statement.
The default case does not have to be the last case in a switch block. However, if it’s not the last, it must end with a break statement to prevent fall-through into subsequent case blocks.
示例:带有 default。
const userRole = "guest";let permissions;
switch (userRole) { case "admin": permissions = "Full access"; break; case "editor": permissions = "Can write and edit content"; break; default: permissions = "Limited access or view only"; // 如果是最后一个子句,则不需要 break}
console.log(`Role: ${userRole}, Permissions: ${permissions}`);It’s important to remember that switch uses strict comparison (===). This means the type and value of the expression must match the type and value of the case.`
const value = "5";
switch (value) { case 5: // 这是数字 5,而 value 是字符串 "5" console.log("Matched number 5"); break; case "5": // 这是字符串 "5",与 value 匹配 console.log("Matched string '5'"); break; default: console.log("No match");}// 输出: Matched string '5'简单查找的 switch 替代方案
Section titled “简单查找的 switch 替代方案”For simple value-to-value mappings, an object literal or a Map can sometimes be a cleaner alternative to a switch statement, especially if there’s no complex logic or fall-through involved.
// Using an object literal for lookupconst fruitColors = { apple: "red or green", banana: "yellow", orange: "orange"};
const selectedFruit = "banana";const color = fruitColors[selectedFruit] || "unknown color";console.log(`The color of ${selectedFruit} is ${color}.`);然而,当每个 case 需要执行超出简单赋值的操作时,或者有意使用穿透逻辑时,switch 仍然非常有用。
有关更多详细信息和示例,请参考 MDN 关于 switch 的文档。