計算 JavaScript 中字串的權重
字元(字母)的權重
英文字母的權重只是其從 1 開始的索引。
例如,'c' 的權重為 3,'k' 的權重為 11,依此類推。
我們要求編寫一個 JavaScript 函式來獲取小寫字串並計算並返回該字串的權重。
示例
程式碼如下 −
const str = 'this is a string'; const calculateWeight = (str = '') => { str = str.toLowerCase(); const legend = 'abcdefghijklmnopqrstuvwxyz'; let weight = 0; const { length: l } = str; for(let i = 0; i < l; i++){ const el = str[i]; const curr = legend.indexOf(el); weight += (curr + 1); }; return weight; }; console.log(calculateWeight(str));
輸出
控制檯中的輸出如下 −
172
廣告