เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่มีความยาวเท่าใดก็ได้ ฟังก์ชันควรนับจำนวนคำในสตริงนั้น
ตัวอย่าง
const str = 'THis is an example string';
const findWords = (str = '') => {
if(!str.length){
return 0;
};
let count = 1;
for(let i = 0; i < str.length; i++){
if(str[i] === ' '){
count++;
};
};
return count;
};
console.log(findWords(str)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
5