使用for循环,中断和继续来查找特定字母出现在句子中的次数-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
热门推荐
3 带清的简短祝福语
10 同事离别祝福语简短的
11 送给老师中秋祝福语简短
12 佛教生日祝福语简短大全
13 公司28 周年祝福语简短
14 晚儿子生日祝福语简短
15 学生开学季祝福语简短
16 身体康复的祝福语简短
17 信耶稣的人祝福语简短
18 婚礼祝福语简短情话短句