字符串的 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));
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
输出
控制台中的输出 −
116
广告