计算 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP