題目連結
解法
Javascript
function high(x){
function calculateScore (word){
const alphabet = "abcdefghijklmnopqrstuvwxyz"
return word.split('').reduce( (score, letter) => score + alphabet.indexOf(letter) + 1 , 0)
}
const words = x.split(' ')
let highestWord = ''
let highestScore = 0
words.forEach( (word) => {
const score = calculateScore(word)
if (score > highestScore || (score === highestScore && word < highestWord.length)){
highestScore = score
highestWord = word
}
})
return highestWord
}
心得
先把x用split(' ')
做拆解
預設兩個值:最高分數和最高分單字
將拆解後的words
進迴圈比大小
同時建立一個轉換分數的function
如果轉換後的分數大於highestScore
和highestWord
就替換掉
同分就比單字的長度
最後回傳(每次都忘記回傳 不然就是設立在迴圈裡頭)