JavaScript 中字符串的 ASCII 和差

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/26 0:12:17

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

相关文章


有用资源