使用 for 循环、break 和 continue 查找特定字母在句子中出现的次数 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/11/24 11:24: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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

