使用 for 循环、break 和 continue 查找特定字母在语句中出现的次数 - 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 年 9 月 14 日

71 次浏览

开启您的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.