我最近开始学习JavaScript,但是有些问题需要你的帮助。下面是一个简单的函数,但是似乎无法正常运行,请告诉我我做错了什么。
function countWords(str) {
/*Complete the function body below to count
the number of words in str. Assume str has at
least one word, e.g. it is not empty. Do so by
counting the number of spaces and adding 1
to the result*/
var count = 0;
for (int 0 = 1; i <= str.length; i++) {
if (str.charAt(i) == " ") {
count ++;
}
}
return count + 1;
}
console.log(countWords("I am a short sentence"));
我遇到了一个错误 SyntaxError: for循环初始化器后缺少分号
感谢您的帮助。
i<str.length
,这样就不会超出字符串的范围了。 - Guffa