比较字符串的 ASCII 分数 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/4 16:44:17
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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

