计算 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));
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
输出
控制台中的输出如下 −
172
广告