Dokumentacja języka JavaScript 1.5:Polecenia:switch
z Mozilla Developer Center, polskiego centrum programistów Mozilli.
UWAGA: Tłumaczenie tej strony nie zostało zakończone.
Może być ona niekompletna lub wymagać korekty.
Chcesz pomóc? | Dokończ tłumaczenie | Sprawdź ortografię | Więcej takich stron...
Spis treści |
[edytuj] Podsumowanie
Evaluates an expression, matching the expression's value to a case label, and executes statements associated with that case.
| Instrukcja | |
| Zaimplementowana w: | JavaScript 1.2, NES 3.0 |
| Wersja ECMA: | ECMA-262, Edycja 3 |
[edytuj] Składnia
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
case labelN:
statementsN
[break;]
default:
statements_def
[break;]
}
[edytuj] Parametry
-
expression - An expression matched against each label.
-
labelN - Identifier used to match against
expression.
-
statementsN - Statements that are executed if
expressionmatches the associated label.
-
statements_def - Statements that are executed if
expressiondoes not match any label.
[edytuj] Opis
If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.
The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. If no matching label 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. By convention, the default clause is the last clause, but it does not need to be so.
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.
[edytuj] Przykłady
[edytuj] Przykład: Zastosowanie switch
In the following example, if expression 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":
document.write("Oranges are $0.59 a pound.<br>");
break;
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
case "Cherries":
document.write("Cherries are $3.00 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + i + ".<br>");
}
document.write("Is there anything else you'd like?<br>");