เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่มีช่องว่าง ฟังก์ชันควรนับจำนวนช่องว่างที่อยู่ในสตริงนั้นอย่างง่ายๆ
เช่น ถ้าสตริงอินพุตคือ:
const str = 'this is a string';
ผลลัพธ์ควรเป็น:
const output = 4;
ตัวอย่าง
const str = 'this is a string';
const countSpaces = (str = '') => {
let count = 0;
for(let i = 0; i < str.length; i++){
const el = str[i];
if(el !== ' '){
continue;
};
count++;
};
return count;
};
console.log(countSpaces(str));
ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ดังนี้:
4