開發專案時,在其中的某個環節,想說除了switch
之外,是否有更好的寫法,上網一查發現,還有switch(true)
這種用法,感覺還蠻新奇的,第一次接觸到的人或許會對expression
裡面怎會是true
感到疑惑。
首先,我們先來討論以下情境:
請依照分數高低,分配SABCD級距。
一般的情況都會這樣寫:
1 2 3 4 5 6 7 8 9 10 11 12 13
| if (score === 100) { level = 'S'; } else if (score >= 90 && score < 100) { level = 'A'; } else if (score >= 80 && score < 90) { level = 'B'; } else if (score >= 70 && score < 80) { level = 'C'; } else if (score >= 60 && score < 70) { level = 'D' } else { level = '不及格' }
|
使用條件(三元)運算子
,更簡潔
1 2 3 4 5 6
| level = score === 100 ? 'S' : score >= 90 && score < 100 ? 'A' : score >= 80 && score < 90 ? 'B' : score >= 70 && score < 80 ? 'C' : score >= 60 && score < 70 ? 'D' : '不及格'
|
最後是今天要討論的主題switch(true)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| switch (true) { case score === 100: level = 'S'; break; case score >= 90 && score < 100: level = 'A'; break; case score >= 80 && score < 90: level = 'B'; break; case score >= 70 && score < 80: level = 'C'; break; case score >= 60 && score < 70: level = 'D'; break; default: level = '不及格'; }
|
為何switch (true)
可行,答案其實很簡單:case條件是用來跟expression匹配的
。
switch
不只是用來比對string
、number
,也可以比對boolean
。
至於可讀性,第二種相對會比較差。
※ 另外補充,在這篇文章中網友提到的另一種方法,也是不錯的選擇
1 2 3 4 5 6 7 8 9
| const level= ((score) => { if(typeof score !== 'number') return 'NAN' if(score===100) return 'S' if(score >= 90 && score < 100) return 'A'; if(score >= 80 && score < 90) return 'B'; if(score >= 70 && score < 80) return 'C'; if(score >= 60 && score < 70) return 'D if(score < 60) return 'F' })(100)
|