查找特定字母在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 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短