这是一个针对字符串中单词“Wrox”的简单搜索计数器的类(class)项目。
我的代码:
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
。它一直有效,直到突然不起作用。我不知道我做错了什么。
最佳答案
String.indexOf
返回-1
当在字符串中找不到您要搜索的子字符串时。
因此,这就是您应该在 while 条件中检查的内容,而不是 i <= myString.length
因为如果i
为正,表示在字符串内部找到了子字符串,因此索引小于长度。
i = myString.indexOf('Wrox');
while (i > 0) {
wroxCount++;
i = myString.indexOf('Wrox', i + 1);
}
关于javascript - 循环计数器重置为-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31277579/