字串的 ASCII 和差


ASCII 碼

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

更新時間:15/10/2020

524 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.