比較字串的 ascii 分數 - JavaScript
ASCII 碼
ASCII 是一種 7 位字元編碼,其中每一位都表示一個唯一的字元。
每個英文單詞都有一個唯一的十進位制 ASCII 碼。
我們需要編寫一個函式,該函式接收兩個字串,並計算它們的 ASCII 分數(即,該字串中每個字元的 ASCII 十進位制數之和),並返回差值。
示例
讓我們為以下內容編寫程式碼 −
const str1 = 'This is the first string.';
const str2 = 'This here is the second string.';
const calculateScore = (str = '') => {
return str.split("").reduce((acc, val) => {
return acc + val.charCodeAt(0);
}, 0);
};
const compareASCII = (str1, str2) => {
const firstScore = calculateScore(str1);
const secondScore = calculateScore(str2);
return Math.abs(firstScore - secondScore);
};
console.log(compareASCII(str1, str2));輸出
以下是控制檯中的輸出 −
536
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP