Chúng ta cần viết hàm JavaScript tìm số lần một ký tự cụ thể xuất hiện trong câu.
Ví dụ
Mã cho việc này:
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){ // dùng continue để chuyển sang lần lặp tiếp theo continue; }; // nếu đến đây nghĩa là str[i] và char giống nhau // tăng count count++; }; return count; }; console.log(countAppearances(string, 'a')); console.log(countAppearances(string, 'e')); console.log(countAppearances(string, 's'));Đầu ra
Kết quả trên console:
3 3 4