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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
|
---
title: switch
slug: Web/JavaScript/Reference/Statements/switch
translation_of: Web/JavaScript/Reference/Statements/switch
---
<div>{{jsSidebar("Statements")}}</div>
<p>The <strong><code>switch</code> statement</strong> evaluates an <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">expression</a>, matching the expression's value to a <code>case</code> clause, and executes <a href="/en-US/docs/Web/JavaScript/Reference/Statements">statements</a> associated with that case, as well as statements in cases that follow the matching case.</p>
<div>{{EmbedInteractiveExample("pages/js/statement-switch.html")}}</div>
<h2 id="문법">문법</h2>
<pre class="brush: js">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><br>
각각의 case 절에 맞추어볼 결과에 대한 <code>expression</code></dd>
<dt><code>case valueN</code> {{optional_inline}}</dt>
<dd>어떤 <code>case</code> 절은 <code>expression</code>와 맞추어보는데 사용된다. 만약 <code>expression</code> 이 특정 <code>valueN</code>과 일치 된다면, <code>switch</code> statement 문이 끝나거나 <code>break</code>가 오떄까지 case 절 내부가 실행된다.</dd>
<dt><code>default</code> {{optional_inline}}</dt>
<dd><code>default</code> 절; 만약 있다면, 어떤 <code>case</code>의 절도 <code>expression</code> 값과 일치되지 않는다면, default 절이 실행된다.</dd>
</dl>
<h2 id="설명">설명</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">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="예제">예제</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="break를_쓰지않으면_어떻게_되는가">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="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 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!');
}</pre>
<p>이 예제의 결과:</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 0</td>
<td>Please pick a number from 0 to 5!</td>
</tr>
<tr>
<td>0</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>
<h3 id="Block-scope_variables_within_switch_statements">Block-scope variables within <code>switch</code> statements</h3>
<p>With ECMAScript 2015 (ES6) support made available in most modern browsers, there will be cases where you would want to use <a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a> statements to declare block-scoped variables.</p>
<p>Take a look at this example:</p>
<pre class="brush: js">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;
}</pre>
<p>This example will output the error <code>Uncaught SyntaxError: Identifier 'message' has already been declared</code> which you were not probably expecting.</p>
<p>This is because the first <code>let message = 'hello';</code> conflicts with second let statement <code>let message = 'hi';</code> even they're within their own separate case statements <code>case 'say_hello':</code> and <code>case 'say_hi':</code>; ultimately this is due to both <code>let</code> statements being interpreted as duplicate declarations of the same variable name within the same block scope.</p>
<p>We can easily fix this by wrapping our case statements with brackets:</p>
<pre class="brush: js">const action = 'say_hello';
switch (action) {
case 'say_hello': <strong>{ // added brackets</strong>
let message = 'hello';
console.log(message);
break;
<strong>} // added brackets</strong>
case 'say_hi': <strong>{ // added brackets</strong>
let message = 'hi';
console.log(message);
break;
<strong>} // added brackets</strong>
default: <strong>{ // added brackets</strong>
console.log('Empty action received.');
break;
<strong>} // added brackets</strong>
}</pre>
<p>This code will now output <code>hello</code> in the console as it should, without any errors at all.</p>
<h2 id="명세">명세</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">명세</th>
<th scope="col">상태</th>
<th scope="col">설명</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="브라우저_호환성">브라우저 호환성</h2>
<p>{{Compat("javascript.statements.switch")}}</p>
<h2 id="같이_보기">같이 보기</h2>
<ul>
<li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else"><code>if...else</code></a></li>
</ul>
|