母音、其他字元和子音在字串 JavaScript 中的差異


我們需要編寫一個函式,該函式接收一個由特定字元組成的字串,並返回該字串中母音加其他字元與子音的數量之間的差值。

例如 −

如果字串為 −

"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

更新於:31-8-2020

148 次瀏覽

開啟你的 職業生涯

透過完成課程取得認證

開始
廣告
© . All rights reserved.