switch (표현식) {
case 표현식1:
//Statements executed when the
//result of expression matches value1
[break;]
case 표현식2:
//Statements executed when the
//result of expression matches value2
[break;]
[default:
//Statements executed when none of
//the values match the value of the expression
[break;]]
}
break 문이 없다면, case문의 표현식과 일치하지 않더라도 실행 흐름이 다음 case 문으로 이동한다.
break 문을 의도적으로 생략하는 폴스루(fall-through)를 사용하기도 한다.
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나 continue 구문과 함께 사용할 수 있다. 원하는 식별자로 구문 앞에 레이블을 추가할 수 있다.
label :
statement
label: 자바스크립트에서 사용할 수 있는 식별자
statement: 구문. break는 모든 레이블 구문에서 사용될 수 있으며, continue는 반복 레이블 구문에서만 사용할 수 있다.
// MDN 예시 (for문에서 레이블 continue 사용하기)
var i, j;
loop1:
for (i = 0; i < 3; i++) { //첫번째 for문은 "loop1" 레이블을 붙였다.
loop2:
for (j = 0; j < 3; j++) { //두번째 for문은 "loop2" 레이블을 붙였다.
if (i === 1 && j === 1) {
continue loop1;
}
console.log('i = ' + i + ', j = ' + j);
}
}
// 출력 결과:
// "i = 0, j = 0"
// "i = 0, j = 1"
// "i = 0, j = 2"
// "i = 1, j = 0"
// "i = 2, j = 0"
// "i = 2, j = 1"
// "i = 2, j = 2"
// 다음 두 경우를 어떻게 스킵하는지 주목 : "i = 1, j = 1", "i = 1, j = 2"
// MDN 예시 (for문에 레이블 break문 사용하기)
var i, j;
loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
break loop1;
}
console.log('i = ' + i + ', j = ' + j);
}
}
// Output is:
// "i = 0, j = 0"
// "i = 0, j = 1"
// "i = 0, j = 2"
// "i = 1, j = 0"
// Notice the difference with the previous continue example
MDN 레이블 구문 예시 보기
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/label