โจทย์
เขียนฟังก์ชันนับว่าตัวอักษรเฉพาะตัวปรากฏกี่ครั้งในประโยค
ตัวอย่างโค้ด
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 ข้ามไป iteration ถัดไป
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
คำอธิบาย
ใช้ continue ข้าม iteration เมื่อตัวอักษรไม่ตรง
เมื่อตรงกัน count++ เพิ่มตัวนับ
ผลลัพธ์: 'a'=3, 'e'=3, 's'=4 ครั้งในประโยคตัวอย่าง