jst*_*one 3 javascript for-loop indexof
我试图计算使用indexOf()在字符串中出现字母的次数.你能告诉我我的代码在哪里出错吗?谢谢!
var string = 'Lets find l as many times as we can. Love is natural, love you lots';
var myFunc = function (letter) {
newString = 0;
for (var i = 0; i < letter.length; i += 1) {
if (string.indexOf('l')) {
newString += 1;
}
}
return newString;
}
Run Code Online (Sandbox Code Playgroud)
而不是这个
if (string.indexOf('l')) {
newString += 1;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用charAt甚至直接索引来检查字符串的每个字母.
像这样
if (letter[i] == 'l') {
newString += 1;
}
Run Code Online (Sandbox Code Playgroud)
或这个
if (letter.charAt(i) == 'l') {
newString += 1;
}
Run Code Online (Sandbox Code Playgroud)
这是一个FIDDLE
请注意,如果你要使用,indexOf你想直接在有问题的字符串上调用它,就像这样
letter.indexOf('l')
另一个答案非常好,但是如果你真的想要一个解决方案indexOf(正如你的问题标题所示),你需要提供第二个参数,告诉它从哪里开始寻找下一个事件:
var myFunc = function (str) {
var i = 0, c = 0;
do {
i = str.indexOf('l', i);
} while (++i && ++c);
return c;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果使用的indexOf是不是一个要求,你可以简化这个给:
var myFunc = function (str) {
return str.split('l').length - 1;
}
Run Code Online (Sandbox Code Playgroud)