简单的 JavaScript 字数统计功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16753732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:51:37  来源:igfitidea点击:

Simple JavaScript Word Count Function

javascript

提问by Val Okafor

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.

我终于开始学习 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"));

I am getting an error SyntaxError: missing ; after for-loop initializer

我收到一个错误 SyntaxError: missing ; after for-loop initializer

Thanks for your assistance

感谢你的协助

回答by Guffa

There is no intkeyword in Javascript, use varto declare a variable. Also, 0can'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:

intJavascript 中没有关键字,用于var声明变量。另外,0不能是变量,我确定您的意思是声明变量i。此外,您应该为字符串中的字符从 0 循环到 length-1:

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

回答by Sachin

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 problems are there is nothing like intin javascript and also you are using 0=1that doesn't make any sense. Just use variable iwith varkeyword.

所以问题是int在 javascript 中没有任何东西,而且你正在使用0=1它没有任何意义。只需使用ivar关键字的变量。

回答by Anish Gupta

This

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

should be

应该

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

There is no keyword intin javascript

intjavascript中没有关键字

回答by sylwia

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");

btw. try to avoid declaring variables inside loop, it's faster when outside

顺便提一句。尽量避免在循环内声明变量,在循环外会更快