在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP