๐Ÿ“—JS: switch statement(switch ๋ฌธ)

summereuna๐Ÿฅยท2022๋…„ 1์›” 17์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
1/9

์Šค์œ„์น˜ ๋ฌธ(switch statement)์€ ํ‘œํ˜„์‹(expression)์˜ ๊ฐ’์„ ์‚ฌ๋ก€ ์ ˆ(case clause)๊ณผ ์ผ์น˜์‹œ์ผœ(===) ํ‘œํ˜„์‹์„ ํ‰๊ฐ€ํ•˜๊ณ , ํ•ด๋‹น ์‚ฌ๋ก€์™€ ๊ด€๋ จ๋œ ๋ฌธ(statement)๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์ผ์น˜ํ•˜๋Š” ์‚ฌ๋ก€(case) ๋’ค์— ์˜ค๋Š” ์‚ฌ๋ก€์˜ ๋ฌธ(statements)๋„ ์‹คํ–‰ํ•œ๋‹ค.

์Šค์œ„์น˜ ๋ฌธ์€ if, if else๋กœ ์ด์–ด์ง€๋Š” ๋ณต์ˆ˜์˜ if ๋ฌธ์„ ๋Œ€์น˜ํ•  ์ˆ˜ ์žˆ๋‹ค. ์‹œ๊ฐ์ ์œผ๋กœ๋„ ์–ด๋–ค ์กฐ๊ฑด/์‚ฌ๋ก€๋“ค์ด ์žˆ๋Š”์ง€ ๋” ์ž˜ ๋ณด์ธ๋‹ค. ๐Ÿ‘€

๐Ÿ“ syntax


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

ํ‘œํ˜„์‹(expression)์˜ ๊ฐ’์„ ์‚ฌ๋ก€ ์ ˆ(case clause)๊ณผ ์ผ์น˜์‹œ์ผœ ํ‘œํ˜„์‹์„ ํ‰๊ฐ€ํ•œ๋‹ค.

case valueN (Optional)

์‚ฌ๋ก€(case)์— ์ง€์ •ํ•œ ๊ฐ’(valueN)๊ณผ ํ‘œํ˜„์‹(expression)์ด ์ผ์น˜ํ•  ๊ฒฝ์šฐ, ์ฆ‰ (expression === valueN)์ธ ๊ฒฝ์šฐ, case์ ˆ์˜ ๋‚ด๋ถ€ ๊ตฌ๋ฌธ์ด ์‹คํ–‰๋œ๋‹ค.

case์˜ valueN์„ ์ž‘์„ฑํ•  ๋•Œ๋Š” Data Type์— ์ฃผ์˜ํ•˜์ž!

case์ ˆ์˜ ๋‚ด๋ถ€๊ตฌ๋ฌธ์€ break;๊ฐ€ ๋‚˜์˜ฌ๋•Œ ๊นŒ์ง€ ์‹คํ–‰๋œ๋‹ค. break;๋ฅผ ๋”ฐ๋กœ ์ž‘์„ฑํ•˜์ง€ ์•Š์œผ๋ฉด ๊ธฐ์ค€์ด ์ถฉ์กฑ๋œ ์‚ฌ๋ก€๊ฐ€ ๋‚˜์™€๋„ ๋๊นŒ์ง€ ์‹คํ–‰ํ•œ๋‹ค. ์ฆ‰, ๊ธฐ์ค€ ์ถฉ์กฑ ์—ฌ๋ถ€์— ๊ด€๊ณ„์—†์ด ๋’ค์— ์žˆ๋Š” ๋ชจ๋“  ์‚ฌ๋ก€, ์Šค์œ„์น˜ ๊ตฌ๋ฌธ์˜ ๋๊นŒ์ง€ ์‹คํ–‰๋˜๊ธฐ ๋•Œ๋ฌธ์— ์ฃผ์˜ํ•˜์ž!

default (Optional)

default ์ ˆ์„ ์ž‘์„ฑํ•ด ๋‘๋ฉด expression ๊ฐ’๊ณผ ์ผ์น˜ํ•˜๋Š” case๊ฐ€ ์—†์„ ๋•Œ default ์ ˆ์ด ์‹คํ–‰๋œ๋‹ค.
default ์ ˆ์„ ์ž‘์„ฑํ•˜๋Š” ์œ„์น˜๋Š” ๋”ฐ๋กœ ์ •ํ•ด์ ธ ์žˆ์ง€ ์•Š๋‹ค. ์ œ์ผ ์ฒซ ๋ถ€๋ถ„์— ์ž‘์„ฑํ•ด๋„ ๋˜๊ณ , case์ ˆ๊ณผ case์ ˆ ์‚ฌ์ด์— ์ž‘์„ฑํ•ด๋„ ๋˜๊ณ , ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„์— ์ž‘์„ฑํ•ด๋„ ๋œ๋‹ค.

๐Ÿ“ ์˜ˆ์‹œ


let bts = 7;
switch (bts) {
  case 13:
    console.log("BTS has 13 members.")
    break;
  case 7:
    console.log("BTS has 7 members.")
    break;
  case 5:
    console.log("BTS has 5 members.")
    break;
}

๊ฒฐ๊ณผ
(bts === 7)์ด๊ธฐ ๋•Œ๋ฌธ์— ์ฝ˜์†”์— "BTS has 7 members."๋ผ๊ณ  ์ถœ๋ ฅ๋œ๋‹ค.


์ฐธ๊ณ : switch - JavaScript | MDN

profile
Always have hope๐Ÿ€ & constant passion๐Ÿ”ฅ

0๊ฐœ์˜ ๋Œ“๊ธ€