尋找特定字母在 JavaScript 語句中出現的次數


我們需要編寫一個 JavaScript 函式,該函式查詢特定字母在語句中出現的次數。

舉例說明

程式碼如下 −

const string = 'This is just an example string for the program';
const countAppearances = (str, char) => {
   let count = 0;
   for(let i = 0; i < str.length; i++){
      if(str[i] !== char){
         // using continue to move to next iteration
         continue;
      };
      // if we reached here it means that str[i] and char are same
      // so we increase the count
      count++;
   };
   return count;
};
console.log(countAppearances(string, 'a'));
console.log(countAppearances(string, 'e'));
console.log(countAppearances(string, 's'));

輸出

控制檯中的輸出 −

3
3
4

更新於: 2020 年 10 月 14 日

421 個觀看

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.