循环计数器重置为-1

时间:2015-07-07 19:25:46

标签: javascript for-loop indexof

这是一个关于单词" Wrox"在一个字符串中。

我的代码:

var myString = "Welcome to Wrox books. ";
myString = myString + "The Wrox website is www.wrox.com. ";
mystring = myString + "Visit the Wrox website today. Thanks for buying Wrox. ";

var i = 0;
var wroxCount = 0;

while (i <= myString.length) {
    i = myString.indexOf("Wrox",i); 
    wroxCount++;  
    i++;
}

i出于某种原因决定重置为-1之前,它可以正常工作。它一直有效,直到它突然没有。我不知道自己做错了什么。

1 个答案:

答案 0 :(得分:1)

当在字符串中找不到您要搜索的子字符串时,

String.indexOf会返回-1

所以这是你应该在while条件下检查的,而不是i <= myString.length,因为如果i为正,则在字符串中找到子字符串,因此索引低于长度。

i = myString.indexOf('Wrox');
while (i > 0) {
    wroxCount++;
    i = myString.indexOf('Wrox', i + 1);
}