switch
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2015å¹´7æ.
switch èªå¥ææ¯å°ä¸å表éå¼è£¡é ç弿¯å¦ç¬¦å case æ¢ä»¶ï¼ç¶å¾å·è¡è·é忢件ç¸éçé³è¿°å¼ï¼ä»¥åæ¤ä¸ç¬¦åæ¢ä»¶ä»¥å¤ï¼å©ä¸å
¶ä»æ¢ä»¶è£¡çé³è¿°å¼ã
å試ä¸ä¸
const expr = "Papayas";
switch (expr) {
case "Oranges":
console.log("Oranges are $0.59 a pound.");
break;
case "Mangoes":
case "Papayas":
console.log("Mangoes and papayas are $2.79 a pound.");
// Expected output: "Mangoes and papayas are $2.79 a pound."
break;
default:
console.log(`Sorry, we are out of ${expr}.`);
}
èªæ³
switch (expression) {
case value1:
//ç¶ expression çå¼ç¬¦å value1
//è¦å·è¡çé³è¿°å¥
[break;]
case value2:
//ç¶ expression çå¼ç¬¦å value2
//è¦å·è¡çé³è¿°å¥
[break;]
...
case valueN:
//ç¶ expression çå¼ç¬¦å valueN
//è¦å·è¡çé³è¿°å¥
[break;]
[default:
//ç¶ expression çå¼é½ä¸ç¬¦åä¸è¿°æ¢ä»¶
//è¦å·è¡çé³è¿°å¥
[break;]]
}
expression-
ä¸å表éå¼å ¶çµæç¨ä¾è·æ¯å
caseæ¢ä»¶æ¯å°ã case valueN鏿æ§-
ä¸å
caseæ¢ä»¶æ¯ç¨ä¾è·expressionå¹é çã 妿expression符åç¹å®çvalueNï¼é£å¨ case æ¢ä»¶è£¡çèªå¥å°±æå·è¡ï¼ç´å°éåswitché³è¿°å¼çµææéå°ä¸åbreakã default鏿æ§-
ä¸å
defaultæ¢ä»¶ï¼åè¥æé忢件ï¼é£å¨expressionçå¼ä¸¦ä¸ç¬¦åä»»ä½ä¸åcaseæ¢ä»¶çæ æ³ä¸ï¼å°±æå·è¡éåæ¢ä»¶è£¡çèªå¥ã
æè¿°
ä¸å switch é³è¿°å¼æå
è©ä¼°èªå·±ç expressionãç¶å¾ä»ææç
§ case æ¢ä»¶é åºéå§å°æ¾ï¼ç´å°æ¯å°å°ç¬¬ä¸å表éå¼å¼è·è¼¸å
¥ expression çå¼ç¸çç case æ¢ä»¶ï¼ä½¿ç¨å´æ ¼çé輯éç®å, ===ï¼ä¸¦ææ§å¶æµäº¤çµ¦è©²åå¥ã並å·è¡è£¡é¢çé³è¿°å¼ï¼å¦æçµ¦å®å¼ç¬¦åå¤å caseï¼å°±å·è¡ç¬¬ä¸å符åç caseï¼å°±ç®è©² case èå
¶ä» case ä¸åï¼
If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. æç
§æ
£ä¾ï¼ default èªå¥ææ¯æå¾ä¸åæ¢ä»¶ï¼ä½ä¸ä¸å®è¦åå¨ã
The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.
ç¯ä¾
>ä½¿ç¨ switch
In the following example, if expr evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.
switch (expr) {
case "Oranges":
console.log("Oranges are $0.59 a pound.");
break;
case "Apples":
console.log("Apples are $0.32 a pound.");
break;
case "Bananas":
console.log("Bananas are $0.48 a pound.");
break;
case "Cherries":
console.log("Cherries are $3.00 a pound.");
break;
case "Mangoes":
case "Papayas":
console.log("Mangoes and papayas are $2.79 a pound.");
break;
default:
console.log("Sorry, we are out of " + expr + ".");
}
console.log("Is there anything else you'd like?");
妿æå¿è¨ break æç¼çä»éº¼äºï¼
If you forget a break then the script will run from the case where the criterion is met and will run the case after that regardless if criterion was met. See example here:
var foo = 0;
switch (foo) {
case -1:
console.log("negative 1");
break;
case 0: // foo is 0 so criteria met here so this block will run
console.log(0);
// NOTE: the forgotten break would have been here
case 1: // no break statement in 'case 0:' so this case will run as well
console.log(1);
break; // it encounters this break so will not continue into 'case 2:'
case 2:
console.log(2);
break;
default:
console.log("default");
}
æå¯ä»¥å¨ cases ä¸éæ¾ default åï¼
Yes, you can! JavaScript will drop you back to the default if it can't find a match:
var foo = 5;
switch (foo) {
case 2:
console.log(2);
break; // it encounters this break so will not continue into 'default:'
default:
console.log("default");
// fall-through
case 1:
console.log("1");
}
It also works when you put default before all other cases.
åæä½¿ç¨å¤åæ¢ä»¶ case çæ¹æ³
Source for this technique is here:
Switch statement multiple cases in JavaScript (Stack Overflow)
Multi-case - single operation
This method takes advantage of the fact that if there is no break below a case statement it will continue to execute the next case statement regardless if the case meets the criteria. See the section titled "What happens if I forgot a break?"
This is an example of a single operation sequential switch statement, where four different values perform exactly the same.
var Animal = "Giraffe";
switch (Animal) {
case "Cow":
case "Giraffe":
case "Dog":
case "Pig":
console.log("This animal will go on Noah's Ark.");
break;
case "Dinosaur":
default:
console.log("This animal will not.");
}
Multi-case - chained operations
This is an example of a multiple-operation sequential switch statement, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the case statements, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these case statements as well.
var foo = 1;
var output = "Output: ";
switch (foo) {
case 0:
output += "So ";
case 1:
output += "What ";
output += "Is ";
case 2:
output += "Your ";
case 3:
output += "Name";
case 4:
output += "?";
console.log(output);
break;
case 5:
output += "!";
console.log(output);
break;
default:
console.log("Please pick a number from 0 to 5!");
}
The output from this example:
| Value | Log text |
|---|---|
| foo is NaN or not 1, 2, 3, 4, 5 or 0 | Please pick a number from 0 to 5! |
| 0 | Output: So What Is Your Name? |
| 1 | Output: What Is Your Name? |
| 2 | Output: Your Name? |
| 3 | Output: Name? |
| 4 | Output: ? |
| 5 | Output: ! |
Block-scope variables within switch statements
With ECMAScript 2015 (ES6) support made available in most modern browsers, there will be cases where you would want to use let and const statements to declare block-scoped variables.
Take a look at this example:
const action = "say_hello";
switch (action) {
case "say_hello":
let message = "hello";
console.log(message);
break;
case "say_hi":
let message = "hi";
console.log(message);
break;
default:
console.log("Empty action received.");
break;
}
This example will output the error Uncaught SyntaxError: Identifier 'message' has already been declared which you were not probably expecting.
This is because the first let message = 'hello'; conflicts with second let statement let message = 'hi'; even they're within their own separate case statements case 'say_hello': and case 'say_hi':; ultimately this is due to both let statements being interpreted as duplicate declarations of the same variable name within the same block scope.
We can easily fix this by wrapping our case statements with brackets:
const action = "say_hello";
switch (action) {
case "say_hello": {
// added brackets
let message = "hello";
console.log(message);
break;
} // added brackets
case "say_hi": {
// added brackets
let message = "hi";
console.log(message);
break;
} // added brackets
default: {
// added brackets
console.log("Empty action received.");
break;
} // added brackets
}
This code will now output hello in the console as it should, without any errors at all.
è¦ç¯
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-switch-statement> |