題目連結
https://www.codewars.com/kata/5266876b8f4bf2da9b000362
解法
- 暴力解法
function likes(names) { if ( names.length === 0){ return 'no one likes this' }else if ( names.length === 1){ return `${names[0]} likes this` }else if ( names.length === 2){ return `${names[0]} and ${names[1]} like this` }else if ( names.length === 3){ return `${names[0]}, ${names[1]} and ${names[2]} like this` }else if ( names.length > 3){ return `${names[0]}, ${names[1]} and ${names.length - 2} others like this` } }
- 轉換成
switch
### 筆記function likes(names) { switch (names.length) { case 0: return 'no one likes this' case 1: return `${names[0]} likes this` case 2: return `${names[0]} and ${names[1]} like this` case 3: return `${names[0]}, ${names[1]} and ${names[2]} like this` default: return `${names[0]}, ${names[1]} and ${names.length - 2} others like this` } }
因為有多種不同的結果
先使用了暴力解法後
發現也可以使用switch
這樣在閱讀上更易讀一些