Simple Word Counting Function in JavaScript

I finally started to learn JavaScript, and for some reason I cannot 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, eg 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 get an error SyntaxError: missing ; after for-loop initializer SyntaxError: missing ; after for-loop initializer

thanks for the help

+4
source share
4 answers

There is no int keyword in Javascript, use var to declare a variable. Also, 0 cannot be a variable, I'm sure you want to declare the variable i . In addition, for characters in a string, it is necessary to execute a cycle from 0 to length-1:

 for (var i = 0; i < str.length; i++) { 
+5
source

I think you want to write this

 for (var i = 0; i <= str.length; i++) 

instead of this

 for (int 0 = 1; i <= str.length; i++) 

So the problem is that there is nothing like int in javascript, and you are also using 0=1 , which makes no sense. Just use the i variable with the var keyword.

+4
source

it

 for (int 0 = 1; i <= str.length; i++) 

it should be

 for (var i = 1; i <= str.length; i++) 

Javascript missing int keyword

+2
source

This is what you wanted:

 function countWords(str) { var count = 0, i, foo = str.length; for (i = 0; i <= foo;i++;) { if (str.charAt(i) == " ") { count ++; } } return console.log(count + 1); } countWords("I am a short sentence"); 

by the way. try to avoid variable declarations inside the loop, faster when outside

+2
source

Source: https://habr.com/ru/post/1482756/


All Articles