【问题标题】:Loop counter resetting to -1循环计数器重置为 -1
【发布时间】:2015-07-07 19:25:46
【问题描述】:

这是一个针对字符串中单词“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 之前,它工作正常。它一直有效,直到它突然不起作用。我不知道我做错了什么。

【问题讨论】:

  • 因为如果您要查找的内容不存在,indexOf 将返回 -1。所以一旦你在你的字符串中找到最后一个Wrox,显然没有更多的 Wroxes 超过那个点,你得到-1。所以你找到 wrox #1, #2, ... #n,然后你回到索引 0 并一遍又一遍地扫描字符串……

标签: javascript for-loop indexof


【解决方案1】:

String.indexOf 在字符串中未找到您要搜索的子字符串时返回-1

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

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

【讨论】:

  • 我不知道。非常感谢!
  • @xa3d 不客气!请记住对有用的答案进行投票,最终accept the answer 解决了您的问题,将您的问题标记为已解决。在这里和your other question。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 2019-12-05
  • 2011-11-26
相关资源
最近更新 更多