我们需要编写一个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