1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
|
---
title: switch
slug: Web/JavaScript/Reference/Statements/switch
tags:
- Dokumentacja_JavaScript
- Dokumentacje
- JavaScript
- Strony_wymagające_dopracowania
- Wszystkie_kategorie
translation_of: Web/JavaScript/Reference/Statements/switch
original_slug: Web/JavaScript/Referencje/Polecenia/switch
---
<div>{{jsSidebar("Statements")}}</div>
<p><span class="seoSummary">Instrukcja switch ocenia wyrażenie, dopasowując wartość wyrażenia do klauzuli case, i wykonuje instrukcje powiązane z tym case, a także instrukcje w przypadkach następujących po dopasowanym przypadku.</span></p>
<div>{{EmbedInteractiveExample("pages/js/statement-switch.html")}}</div>
<p class="hidden">Źródło tego interaktywnego przykładu jest przechowywane w repozytorium GitHub. Jeśli chcesz przyczynić się do projektu interaktywnych przykładów, sklonuj https://github.com/mdn/interactive-examples i wyślij nam prośbę o pobranie.</p>
<h2 id="Syntax">Syntax</h2>
<pre class="syntaxbox">switch (expression) {
case value1:
//Statements executed when the
//result of expression matches value1
[break;]
case value2:
//Statements executed when the
//result of expression matches value2
[break;]
...
case valueN:
//Statements executed when the
//result of expression matches valueN
[break;]
[default:
//Statements executed when none of
//the values match the value of the expression
[break;]]
}</pre>
<dl>
<dt><code>expression</code></dt>
<dd>Wyrażenie, którego wynik jest dopasowany do każdej klauzuli przypadku.</dd>
<dt><code>case valueN</code> {{optional_inline}}</dt>
<dd>Klauzula przypadku używana do dopasowania do wyrażenia. Jeśli wyrażenie pasuje do podanej wartościN, instrukcje wewnątrz klauzuli case są wykonywane do końca instrukcji switch lub break.</dd>
<dt><code>default</code> {{optional_inline}}</dt>
<dd>A <code>default</code> clause; if provided, this clause is executed if the value of <code>expression</code> doesn't match any of the <code>case</code> clauses.</dd>
</dl>
<h2 id="Description">Description</h2>
<p>A switch statement first evaluates its expression. It then looks for the first <code>case</code> clause whose expression evaluates to the same value as the result of the input expression (using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">strict comparison</a>, <code>===</code>) and transfers control to that clause, executing 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.)</p>
<p>If no matching <code>case</code> clause is found, the program looks for the optional <code>default</code> clause, and if found, transfers control to that clause, executing the associated statements. If no <code>default</code> clause is found, the program continues execution at the statement following the end of <code>switch</code>. By convention, the <code>default</code> clause is the last clause, but it does not need to be so.</p>
<p>The optional <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/break" title="JavaScript/Reference/Statements/break">break</a></code> 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 <code>break</code> is omitted, the program continues execution at the next statement in the <code>switch</code> statement.</p>
<h2 id="Examples">Examples</h2>
<h3 id="Using_switch">Using <code>switch</code></h3>
<p>In the following example, if <code>expr</code> evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When <code>break</code> is encountered, the program breaks out of <code>switch</code> and executes the statement following <code>switch</code>. If <code>break</code> were omitted, the statement for case "Cherries" would also be executed.</p>
<pre class="brush: js">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?");
</pre>
<h3 id="What_happens_if_I_forgot_a_break">What happens if I forgot a break?</h3>
<p>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:</p>
<pre class="brush: js">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');
}</pre>
<h3 id="Can_I_put_a_default_between_cases">Can I put a default between cases?</h3>
<p>Yes, you can! JavaScript will drop you back to the default if it can't find a match:</p>
<pre class="brush: js">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');
}
</pre>
<p>It also works when you put default before all other cases.</p>
<h3 id="Rewriting_multiple_If_statements_with_Switch">Rewriting multiple If statements with Switch</h3>
<p>Shown below as a possibility.</p>
<pre class="brush: js">var a = 100;
var b = NaN;
switch (true) {
case isNaN(a) || isNaN(b):
console.log('NaNNaN');
break;
case a === b:
console.log(0);
break;
case a < b:
console.log(-1);
break;
default:
console.log(1);
}
</pre>
<h3 id="Methods_for_multi-criteria_case">Methods for multi-criteria case</h3>
<p>Source for this technique is here:</p>
<p><a href="http://stackoverflow.com/questions/13207927/switch-statement-multiple-cases-in-javascript">Switch statement multiple cases in JavaScript (Stack Overflow)</a></p>
<h4 id="Multi-case_-_single_operation">Multi-case - single operation</h4>
<p>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?"</p>
<p>This is an example of a single operation sequential switch statement, where four different values perform exactly the same.</p>
<pre class="brush: js">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.');
}</pre>
<h4 id="Multi-case_-_chained_operations">Multi-case - chained operations</h4>
<p>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.</p>
<pre class="brush: js">var foo = 1;
var output = 'Output: ';
switch (foo) {
case 10:
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 6!');
}</pre>
<p>The output from this example:</p>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Value</th>
<th scope="col">Log text</th>
</tr>
<tr>
<td>foo is NaN or not 1, 2, 3, 4, 5 or 10</td>
<td>Please pick a number from 0 to 6!</td>
</tr>
<tr>
<td>10</td>
<td>Output: So What Is Your Name?</td>
</tr>
<tr>
<td>1</td>
<td>Output: What Is Your Name?</td>
</tr>
<tr>
<td>2</td>
<td>Output: Your Name?</td>
</tr>
<tr>
<td>3</td>
<td>Output: Name?</td>
</tr>
<tr>
<td>4</td>
<td>Output: ?</td>
</tr>
<tr>
<td>5</td>
<td>Output: !</td>
</tr>
</tbody>
</table>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('ES3')}}</td>
<td>{{Spec2('ES3')}}</td>
<td>Initial definition. Implemented in JavaScript 1.2</td>
</tr>
<tr>
<td>{{SpecName('ES5.1', '#sec-12.11', 'switch statement')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td></td>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}</td>
<td>{{Spec2('ES6')}}</td>
<td></td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td></td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{Compat("javascript.statements.switch")}}</p>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else"><code>if...else</code></a></li>
</ul>
|