switch/case ๋ฌธ์ ์ฌ๋ฌ๊ฐ์ง case ์กฐ๊ฑด ์ค ๋ง๋ ์กฐ๊ฑด์ ์ถฉ์กฑ์ํค๋ case๋ฅผ ์คํํ๋ ๋ฌธ์ด๋ค.
const value1 = 1
const value2 = 2
const value3 = 3
const expression = value2
switch(expression){
case value1 :
console.log(`value is ${value1}`)
break
case value2 :
console.log(`value is ${value2}`)
break
case value3 :
console.log(`value is ${value3}`)
break
default :
console.log(`value is ${expression}`)
}
switch์ ์ธ์ ์์ ๊ฐ์ ์ถฉ์กฑ์ํค๋ case ๊ตฌ๋ฌธ์ด ์คํ๋๋ค.
์ ์์ ์์ switch ์ธ์๊ฐ์ด value2๋ผ๋ฉด value2 statement(value is 2)๊ฐ ์คํ๋๋ค.
switch(expression)
switch๋ ์ธ์์์ ๊ฐ์ ํ ๋นํ๋ค.
ํ ๋นํ๋ ๊ฐ์ case ๊ฐ๋ค ์ค ํ๋์ด์์ด ๋ ์ ์๊ณ case ๊ฐ ์ค ์์ด default ๊ฐ์ผ๋ก๋ ์คํ๋ ์ ์๋ค.
switch(expr){
case1 value1:
case2 value2:
defalut:
}
case๋ switch์ ์ธ์๋ฅผ ์ถฉ์กฑ์ํฌ ์ ์๋ ์กฐ๊ฑด๊ฐ์ด๋ค.
switch์ ์ธ์ ์ค ์ถฉ์กฑํ๋ case๊ฐ ์๋ค๋ฉด default๊ฐ์ด ์คํ๋๋ค.
const value1 = 1
const value2 = 2
const value3 = 3
const expression = 5
switch(expression){
default :
console.log(`value is ${expression}`)
case value1 :
console.log(`value is ${value1}`)
case value2 :
console.log(`value is ${value2}`)
break;
case value3 :
console.log(`value is ${value3}`)
}
const value1 = 1
const value2 = 2
const value3 = 3
const expression = 5
switch(expression){
case value1 :
console.log(`value is ${value1}`)
case value2 :
console.log(`value is ${value2}`)
break;
default :
console.log(`value is ${expression}`)
case value3 :
console.log(`value is ${value3}`)
}
default ๊ตฌ๋ฌธ์ ์ด๋์๋ ๋ฃ์ ์ ์๋ค.
case์ break๊ฐ ์๋ค๋ฉด ๋ค์๊ตฌ๋ฌธ๊น์ง ์คํ์ด ๋๋ค.
const value1 = 1
const value2 = 2
const value3 = 3
const expression = value1
switch(expression){
case value1 :
console.log(`value is ${value1}`)
case value2 :
console.log(`value is ${value2}`)
case value3 :
console.log(`value is ${value3}`)
default :
console.log(`value is ${expression}`)
}
์ ๊ฐ์ ๊ฒฝ์ฐ switch์ ์ธ์์ value1์ ํ ๋นํ์์ ๋ , case value1,2,3์ break๊ฐ ์๊ธฐ ๋๋ฌธ์ ๋ชจ๋ ๊ตฌ๋ฌธ์ด ์คํ๋๋ค.
const value1 = 1
const value2 = 2
const value3 = 3
const expression = value1
switch(expression){
case value1 :
console.log(`value is ${value1}`)
case value2 :
console.log(`value is ${value2}`)
break;
case value3 :
console.log(`value is ${value3}`)
default :
console.log(`value is ${expression}`)
}
ํ์ง๋ง case ์ค break๋ฅผ ํ ๋นํ๋ ๋ถ๋ถ์ด ์๋ค๋ฉด ํด๋น case๊น์ง ์คํ๋๊ณ ๋ฌธ์ด ์ข ๋ฃ๊ฐ ๋๋ค.
์ ๊ฐ์ ๊ฒฝ์ฐ์๋ value1์ ํ ๋นํ์์ ๋, case value2๊น์ง๋ง ์คํ์ด ๋๋ค.
const value1 = 1
const value2 = 2
const value3 = 3
const expression = 5
switch(expression){
default :
console.log(`value is ${expression}`)
case value1 :
console.log(`value is ${value1}`)
case value2 :
console.log(`value is ${value2}`)
break;
case value3 :
console.log(`value is ${value3}`)
}
์ ์์ ์ ๊ฒฝ์ฐ์์ ๋ง์ฝ expression ๊ฐ์ case์ ์กด์ฌํ์ง ์๋ ๊ฐ์ ํ ๋นํ๋ฉด default๊ตฌ๋ฌธ๋ถํฐ ์์ํ์ฌ case value2 ๊ตฌ๋ฌธ๊น์ง ์คํ์ด ๋๋ค.