【发布时间】:2015-07-14 14:25:12
【问题描述】:
我正在编写一个函数,它将字符串作为参数,检查给定字符(在本例中为“B”),然后返回一个整数,该整数反映该字符出现的次数。我知道这可以使用正则表达式等来完成,但是我使用的教程到目前为止没有提到正则表达式。代码时间:
function countBs(string) {
var i = 0;
var n = 0;
var position = string.charAt(n);
while (i < string.length) {
if (string.charAt(n) == "B")
n += 1;
i++; //This line causes the following else statement to throw a syntax error. But it's the only way I can think of to have the loop continue iteration *while* checking for equivalence to "B"
else
i++;
return n;
}
}
然后检查console.log(countBs("ABBA"));
【问题讨论】:
-
运行此代码时,会出现控制台错误。在 Chrome devtools 中,它是“SyntaxError: Unexpected token else”。你看控制台了吗?那会提醒你这个问题。一般来说,在发布到 SO 之前始终查看控制台是否有错误是一个好主意。这里的人不是语法检查员。
-
是的,我看到了语法错误,并在我注释掉的行中提到了它。我不确定我为什么会得到它,但从@karma_geek 的回复中意识到这是由于缺少花括号。到目前为止,我所遵循的教程还没有使用花括号来执行条件代码。所以我很茫然。
标签: javascript if-statement while-loop