查找特定字母在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){
//使用继续移动到下一个迭代
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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短