在 JavaScript 中查找特定字母在句子中出现的次数

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/24 22:04:17

我们需要编写一个 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){
         // 使用 continue 移动到下一次迭代
         continue;
      };
      // 如果我们到达这里,则意味着 str[i] 和 char 相同
      // 所以我们增加计数
      count++;
   };
   return count;
};
console.log(countAppearances(string, 'a'));
console.log(countAppearances(string, 'e'));
console.log(countAppearances(string, 's'));

输出

控制台中的输出 −

3
3
4

相关文章


有用资源