我正在浏览“开始使用Javascript”这本书,其中有一个使用while循环的示例,该循环返回单词" Wrox"是一个字符串。
var myString = "Welcome to Wrox books. " +
"The Wrox website is www.wrox.com. " +
"Visit the Wrox website today. Thanks for buying Wrox";
var foundAtPosition = 0;
var wroxCount = 0;
while (foundAtPosition != -1) {
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);
if (foundAtPosition != -1) {
wroxCount++;
foundAtPosition++;
}
}
document.write("There are " + wroxCount + " occurrences of the word Wrox");
不知怎的,它返回4,但似乎应该返回更高的数字。为什么wnxCount不大?像这些中的每一个都是一个事件
W - > Wrox | wroxCount = 1
我们 - > Wrox | wroxCount = 2
Wel - > Wrox | wroxCount = 3
Welc - > Wrox | wroxCount = 4
Welco - > Wrox | wroxCount = 5
欢迎 - > Wrox | wroxCount = 6
欢迎 - > Wrox | wroxCount = 7
在第一个Wrox中一直到r然后在找到第二个,第三个和第四个Wrox之前表现相同。为什么wroxCount只有4?
答案 0 :(得分:2)
您可以使用正则表达式
var myString = "Welcome to Wrox books. " +
"The Wrox website is www.wrox.com. " +
"Visit the Wrox website today. Thanks for buying Wrox";
alert(myString.match(/Wrox/g).length)
或者如果你想找到小写字母匹配,那么
var myString = "Welcome to Wrox books. " +
"The Wrox website is www.wrox.com. " +
"Visit the Wrox website today. Thanks for buying Wrox";
alert(myString.match(/Wrox/ig).length)
答案 1 :(得分:1)
大小写不匹配。您需要将字符串转换为相同的大小写。试试这个:
var myString = "Welcome to Wrox books. " +
"The Wrox website is www.wrox.com. " +
"Visit the Wrox website today. Thanks for buying Wrox";
var foundAtPosition = 0;
var wroxCount = 0;
while (foundAtPosition != -1) {
foundAtPosition = myString.toLowerCase().indexOf("Wrox".toLowerCase(), foundAtPosition);
if (foundAtPosition != -1) {
wroxCount++;
foundAtPosition++;
}
}
document.write("There are " + wroxCount + " occurrences of the word Wrox");
答案 2 :(得分:1)
wroxCount 和的原因应该是 4是indexOf的第二个参数是起始位置
在循环的每次迭代中,起始位置设置为单词Wrox + 1的最后定位索引,因此第一次开始后每个循环开始在前一个匹配的rox位上查找单词Wrox
如果你扫描字符串,确实有四次出现Wrox这个词(wrox不匹配,因为这是区分大小写的匹配)
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);
foundAtPosition将是myString中单词Wrox的索引,输入IN到indexOf函数的参数将是前一个匹配的结果(+1)
答案 3 :(得分:0)
我认为你的程序应该返回5而不是4,但不是更高的数字。你的字符串中出现了5个单词wrox。
正如另一位回答指出的那样,你必须纠正大小写。
foundAtPosition = myString.indexOf("Wrox".toLowerCase(), foundAtPosition);
除此之外,程序按预期运行。在第一个循环中,它在整个原始字符串中搜索单词wrox。它跟踪字符串中第一次出现的位置。第二次,它再次搜索字符串。这次,搜索受限于第一次出现单词wrox直到字符串结束。然后它跟踪第二次出现的wrox。它一直这样做,直到找不到这个词为止。