Javascript 单词计数器
Javascript word counter
我想根据句子中的空格数量制作一个基本的单词计数器,但由于某些原因它不起作用。
function countWords(str) {
if (typeof str == "string" && str.length > 0) {
var counter = 1;
for (var i; i < str.length; i++) {
if (str[i] === " ") {
counter += 1;
}
}
return counter;
} else {
throw Error("You must input a string.");
}
}
console.log(countWords("hello World"));
这会抛出 1 而不是 2。
将 i
初始化为零。
将for (var i;
替换为for (var i=0;
您必须在 for 中初始化计数器,例如 var i = 0;
这是您的代码
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
countWords("hello World");
或者您可以使用 str.split(" ").length
来计算字数
你不应该为此使用循环。您宁愿将字符串拆分为 space 并获取结果数组的长度
let countWords = str => str.split(' ').length;
console.log(countWords("foo bar"));
你的 for 循环是错误的
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i = 0;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
var str = "hello World this is me";
console.log(countWords(str));
我想根据句子中的空格数量制作一个基本的单词计数器,但由于某些原因它不起作用。
function countWords(str) {
if (typeof str == "string" && str.length > 0) {
var counter = 1;
for (var i; i < str.length; i++) {
if (str[i] === " ") {
counter += 1;
}
}
return counter;
} else {
throw Error("You must input a string.");
}
}
console.log(countWords("hello World"));
这会抛出 1 而不是 2。
将 i
初始化为零。
将for (var i;
替换为for (var i=0;
您必须在 for 中初始化计数器,例如 var i = 0;
这是您的代码
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
countWords("hello World");
或者您可以使用 str.split(" ").length
你不应该为此使用循环。您宁愿将字符串拆分为 space 并获取结果数组的长度
let countWords = str => str.split(' ').length;
console.log(countWords("foo bar"));
你的 for 循环是错误的
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i = 0;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
var str = "hello World this is me";
console.log(countWords(str));