在 JavaScript 中查詢小寫字母字串的基於 1 的索引得分


問題

我們需要編寫一個 JavaScript 函式,該函式接受一個字母小寫字串。字母表中 'a' 的索引為 1,'b' 的索引為 2,'c' 的索引為 3... 'z' 的索引為 26。

我們的函式應計算字串的所有字元索引並返回結果。

示例

程式碼如下 -

 線上演示

const str = 'lowercasestring';
const findScore = (str = '') => {
   const alpha = 'abcdefghijklmnopqrstuvwxyz';
   let score = 0;
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      const index = alpha.indexOf(el);
      score += (index + 1);
   };
   return score;
};
console.log(findScore(str));

輸出

控制檯輸出如下 -

188

更新於: 20-Apr-2021

131 瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

開始吧
廣告
© . All rights reserved.