简单的JavaScript字数统计函数

简单的JavaScript字数统计函数,javascript,Javascript,我终于开始学习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

我终于开始学习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"));
函数countWords(str){
/*完成下面的函数体进行计数
str中的字数。假设str在
至少一个单词,例如,它不是空的。请按
计算空格数并添加1
结果*/
var计数=0;

对于(int 0=1;i我想你想写这个

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

对于(var i=0;iJavascript中没有
int
关键字,请使用
var
声明变量。此外,
0
不能是变量,我确信您的意思是声明变量
i
。此外,您应该为字符串中的字符从0循环到长度-1:

for (var i = 0; i < str.length; i++) {
for(变量i=0;i
这个


for(int 0=1;i这是您想要的:

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");
函数countWords(str){
变量计数=0,
我
foo=str.length;

for(i=0;for循环构造的i应为:for(var i=0;i@Nile:实际上,
I在字符串中的每个字符之间循环将非常低效。我建议您执行以下str.split(“”)。lengthperfect,就是这样。感谢您让我在学习JS的过程中摆脱困境
for (int 0 = 1; i <= str.length; i++)
for (var i = 1; i <= str.length; i++)
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");