Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

switch

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

switch표현식의 값에 따라, 각 case문 중 일치하는 위치의 구문을 실행합니다.

구문

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;]
}
expression
case 에서 나타날 것으로 예상되는 값을 반환하는 표현식입니다.
case valueN
expression의 반환할 예상 값입니다.

설명

switch 문은 먼저 괄호 안의 표현식의 값을 확인합니다. 그 다음 구문 내에 처음을 나타난 case 문과 값이 일치하는지 확인합니다. (이때 일치 여부는 ===, 일치연산자를 이용합니다) 이때 일치한다면 해당 case 문 내의 코드가 break를 만날 때까지 실행됩니다. (만약 한 값에 대해 일치하는 여러 case문이 있다면 제일 첫번째 일치된 부분만 실행됩니다.) 만약 제공된 case 문에 모두 일치하는데 실패한 경우, switch 문 내부에 default 문이 주어져 있는지 찾고, 있다면 default문 내의 코드를 실행합니다. default문은 선택사항으로, 생략할 수 있습니다. case문이 모두 매치된 후에 default가 실행되기에, default문은 가장 마지막에 적힙니다. 다만 반드시 마지막에 작성할 필요는 없습니다.

예제

switch 사용

아래 예제에서는 expr이 "Bananas"인 경우 "Bananas"에 해당하는 case문 내부의 코드를 실행합니다. 실행 도중 break이 발견되면 프로그램은 switch문을 빠져나가 switch문 이후에 이어진 코드를 실행합니다. 만약 "Bananas"가 위치한 case문 내에 break가 생략되면, expr이 "Cherries"와 일치하지 않아도 바로 아래에 있는 "Cherries"내의 코드까지 이어서 실행되며, "Cherries"내의 break를 만나 switch문을 나가게 됩니다.

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문을 생략하는 경우

break문을 생략하게 되면 일치되는 case문부터 시작하여 break을 만날때까지, 설령 값이 일치하지 않더라도 이어져 실행됩니다. 아래 예제를 참고해주십시오.

var foo = 0;
switch (foo) {
  case -1:
    console.log('negative 1');
    break;
  case 0: // foo 변수는 현재 0이라는 값을 가지고 있습니다. 여기서부터 실행합니다.
    console.log(0);
    // NOTE: 원래 이 자리에 break가 있어야 합니다. 예시로 들기위해 생략했습니다.
  case 1: // 'case 0:'에서 break가 없었기 때문에, 일치여부에 상관없이 이어져 실행됩니다.
    console.log(1);
    break; // break문을 만났습니다. 'case 2:'로 내려가지 않습니다.
  case 2:
    console.log(2);
    break;
  default:
    console.log('default');
}

여러 값에 대해 동일한 코드를 실행하는 경우

이 기법의 출처는 다음 링크입니다: Switch statement multiple cases in JavaScript (Stack Overflow)

다중 case문 - 단일 실행문

이 기법은 break문을 만날 때까지, 처음 일치된 case문부터의 코드 실행이 이어진다는 switch문의 특성을 활용합니다. 자세한 설명은 "break문을 생략하는 경우" 섹션을 참고해주십시오.

아래 예제는 서로 다른 4개의 값에도 같은 코드를 실행하여 같은 결과를 냅니다.

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.');
}

복합 case문 - 연쇄 실행문

제공된 변수에 따라 시작지점이 바뀌어 다양한 출력을 얻을 수 있는 예제입니다. 이를 통해 switch문은 case문을 코드상에 놓여있는 순서대로 실행하는 것을 알 수 있으며, 입력값을 정렬한 순서대로 실행되는게 아님을 마찬가지로 확인할 수 있습니다. 자바스크립트에서는 case에 일치할 값으로 문자열을 사용할 수도 있습니다.

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!');
}

foo의 값에 따라 나오는 출력은 아래와 같이 다양합니다.

foo의 값 출력
NaN 또는 1, 2, 3, 4, 5, 10 외의 값 Please pick a number from 0 to 6!
10 Output: So What Is Your Name?
1 Output: What Is Your Name?
2 Output: Your Name?
3 Output: Name?
4 Output: ?
5 Output: !

명세

Specification Status Comment
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.2
ECMAScript 5.1 (ECMA-262)
The definition of 'switch statement' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'switch statement' in that specification.
Standard  
ECMAScript 2017 Draft (ECMA-262)
The definition of 'switch statement' in that specification.
Draft  

브라우저 호환성

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

같이 보기

문서 태그 및 공헌자

 이 페이지의 공헌자: nidev
 최종 변경: nidev,