2021. 8. 20. 23:53ใ๐ TIL
โ ์๋ฐ์คํฌ๋ฆฝํธ in ์ฐ์ฐ์ : ์๋ชป ์๊ณ ์์๋ ์
switch(true) ๋ถ๊ธฐ๋ฌธ์ ์ฌ์ฉํ๊ธฐ ์ํด case ๊ตฌ๋ฌธ์ in ์ฐ์ฐ์๋ฅผ ์ ์ฉํ๋ค.
๋ฐฐ์ด์ ์ํ ์์๊ฐ์ in ์ฐ์ฐ์ ์์ ๋ช ์ํ์ฌ, ํด๋น ์์๊ฐ ๋ฐฐ์ด์ ์กด์ฌํ๋ฉด true ๋ฅผ , ๊ทธ๋ ์ง ์์ผ๋ฉด false ๋ฅผ ๋ฆฌํดํ ๊ฒ์ด๋ผ ์๊ฐํ๋ค.
์๋ ์ฝ๋์์ ์ ์ฉํ In ์ฐ์ฐ์๊ฐ ๋น์ฐํ ์ ๋๋ก ์๋ํ ๊ฒ์ด๋ผ ์๊ฐํ์ง๋ง ๊ฒฐ๊ณผ์ ์ผ๋ก ๋ถ๊ธฐ๋ฅผ ํ์ง ์์๋ค.
const result = []
const IE = ["I", "E"]
const SN = ["S", "N"]
const TF = ["T", "F"]
const JP = ["J", "P"]
const switchResult = (key) => { // key = "I" || "E" || "S" || "N" ... || "P"
switch (true) {
case key in IE:
result[0] = key
break
case key in SN:
result[1] = key
break
case key in TF:
result[2] = key
break
case key in JP:
result[3] = key
break
}
}
mdn ์์ ๋ต์ ์ฐพ์ ์ ์์๋ค.
๋ฐ๋ก ๋ฐฐ์ด์์ ์ฐพ๊ณ ์ ํ๋ ์์ ๊ฐ์ ๋ช ์ํ๋ ๊ฒ์ด ์๋๋ผ, ๋ฐฐ์ด์ ์ธ๋ฑ์ค ๊ฐ์ ๋ช ์ํด์ฃผ์ด์ผ ํ๋ค.
ํด์ ์ฐํ์ฑ ์ผ๋ก ์๋์ฒ๋ผ includes() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ค.
const switchResult = (key) => {
switch (true) {
case IE.includes(key):
result[0] = key
break
case SN.includes(key):
result[1] = key
break
case TF.includes(key):
result[2] = key
break
case JP.includes(key):
result[3] = key
break
}
}
๐ฟ switch ~ case ๋ถ๊ธฐ๋ฌธ์์์ OR ์กฐ๊ฑด ์ ์ฉ ๋ฐฉ๋ฒ
switch ๋ฌธ์์ or ์ฐ์ฐ์๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉํ ์ค์๋ฅผ ๋ฒํ๋ค.
case ๋ฌธ์ or ์ฐ์ฐ์๋ฅผ ๊ทธ๋๋ก ์ ์ฉํ ๊ฒ์ด ์๋๋ผ,
ํผ์ฐ์ฐ์๋ค์ ๊ฐ๊ฐ์ case ์ ๋ฐ๋ก ์ ์ฉํด์ผ ํ๋ค.
// wrong way
const switchResult = (key) => {
switch (key) {
case "I" || "E":
result[0] = key
break
case "F" || "T":
result[2] = key
break
case "S" || "N":
result[1] = key
break
case "P" || "J":
result[3] = key
break
}
}
// right way
const switchResult = (key) => {
switch (key) {
case "I":
case "E":
result[0] = key
break
case "F":
case "T":
result[2] = key
break
case "S":
case "N":
result[1] = key
break
case "P":
case "J":
result[3] = key
break
}
}