我们需要编写一个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