创建一个接受字符串并返回字数的函数。该字符串将是一个句子。
示例输出:
countWords("This is a test") ➞ 4
代码
function countWords(str) {
let count = 0;
[...str].forEach(x => x.length > 0)
count++
return count
}
countWords("Hello World")
调用此函数时,我得到undefined is not iterable
。我使用传播运算符错了吗?
此外,是否有一种方法可以在forEach或其他范围内以不太冗长的方式获取计数?我认为增量必须在forEach内,但不确定将其放在何处。
答案 0 :(得分:2)
您可以简单地分割带有空格字符的字符串以创建一个数组,并返回该数组的 length :
function countWords(str) {
let count = str.split(' ').length;
return count;
}
console.log(countWords("This is a test"));
答案 1 :(得分:0)
尝试使用此代码
function countWords(){
s = document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
document.getElementById("wordcount").value = s.split(' ').length;
}
<textarea id="inputString" cols="50" rows="4">Text to count</textarea>
<br>
<input type="button" name="Convert" value="Count Words" onClick="countWords()">
<input id="wordcount" type="text" value="" size="6">