Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความต่างของ ASCII sum ของสตริงใน JavaScript

ASCII Code:

ASCII เป็นรหัสตัวอักษร 7 บิต ที่แต่ละบิตแทนตัวอักษรที่ไม่ซ้ำกัน ทุกตัวอักษรอังกฤษมีรหัส ASCII ทศนิยมที่ไม่ซ้ำกัน

เราต้องเขียนฟังก์ชันที่รับสองสตริงและคำนวณคะแนน ASCII (ผลรวมรหัส ASCII ทศนิยมของแต่ละตัวอักษร) และคืนค่าความต่าง

ตัวอย่าง

โค้ดสำหรับนี้:

const str1 = 'This is an example sting'; const str2 = 'This is the second string'; const calculateScore = (str = '') => { return str.split('').reduce((acc, val) => { return acc + val.charCodeAt(0); }, 0); }; const ASCIIDifference = (str1, str2) => { const firstScore = calculateScore(str1); const secondScore = calculateScore(str2); return Math.abs(firstScore - secondScore); }; console.log(ASCIIDifference(str1, str2));

ผลลัพธ์

ผลลัพธ์ในคอนโซล:

116