เราจำเป็นต้องเขียนฟังก์ชัน 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