น้ำหนักของตัวอักษร (อักษรอังกฤษ)
น้ำหนักของอักษรอังกฤษคือดัชนี 1-based ของมัน
เช่น น้ำหนักของ '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