I finally started to learn JavaScript and for some reason I can't get this simple function to work. Please tell me what I am doing wrong.
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"));
I am getting an error SyntaxError: missing ; after for-loop initializer
Thanks for your assistance
There is no int keyword in Javascript, use var to declare a variable. Also, 0 can't be a variable, I'm sure that you mean to declare the variable i. Also, you should loop from 0 to length-1 for the characters in a string:
for (var i = 0; i < str.length; i++) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With