我试图以这种方式计算文本中的单词:
function WordCount(str) {
var totalSoFar = 0;
for (var i = 0; i < WordCount.length; i++)
if (str(i) === " ") { // if a space is found in str
totalSoFar = +1; // add 1 to total so far
}
totalsoFar += 1; // add 1 to totalsoFar to account for extra space since 1 space = 2 words
}
console.log(WordCount("Random String"));
我认为我已经很好地理解了这一点,只是我认为 if
语句是错误的。检查 str(i)
是否包含空格并加 1 的部分。
编辑:
我发现(感谢 Blender)我可以用更少的代码做到这一点:
function WordCount(str) {
return str.split(" ").length;
}
console.log(WordCount("hello world"));
原文由 user2755667 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用方括号,而不是括号:
或
charAt
:你也可以用
.split()
来做: