简单的 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
Simple JavaScript Word Count Function
提问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 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:
int
Javascript 中没有关键字,用于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 int
in javascript and also you are using 0=1
that doesn't make any sense. Just use variable i
with var
keyword.
所以问题是int
在 javascript 中没有任何东西,而且你正在使用0=1
它没有任何意义。只需使用i
带var
关键字的变量。
回答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 int
in javascript
int
javascript中没有关键字
回答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
顺便提一句。尽量避免在循环内声明变量,在循环外会更快