比較字串的 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

更新於: 15-9 月-2020

992 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.