JavaScript 字符串中元音、其他字符和辅音的差异

javascriptweb developmentobject oriented programming更新于 2025/10/24 17:16:17

我们需要编写一个函数,该函数接受一个确定字符的字符串,并且该函数应返回字符串中元音加上其他字符和辅音的数量之间的差异。

例如 −

如果字符串是 −

"HEllo World!!"

那么,我们有 7 个辅音、3 个元音和 3 个其他字符,因此输出应该是 −

|7 - (3+3)| = 1

因此,输出应该是 1

让我们来编写该函数的代码 −

示例

const str = 'HEllo World!!';
const findDifference = str => {
   const creds = str.split("").reduce((acc, val) => {
      let { v, c } = acc;
      const vowels = 'aeiou';
      const ascii = val.toLowerCase().charCodeAt();
      if(!vowels.includes(val.toLowerCase()) && ascii >= 97 && ascii <=122){
         ++c;
         }else{
            ++v
         };
         return {c,v};
      }, {
         v: 0,
         c: 0
   });
   return Math.abs(creds.c - creds.v);
}
console.log(findDifference(str))

输出

控制台中的输出将是 −

1

相关文章


有用资源