要阻止循环foundAtPosition
需要等于-1
,那该怎么办?
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 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");
答案 0 :(得分:1)
我不明白为什么这个循环不是无限的
如果你没有传递第二个参数foundAtPosition
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);
但是,既然你传递了这个参数,那么第二次它会从(在foundAtPosition
索引之后)查看,最终会有-1
答案 1 :(得分:0)
while
循环正在执行,而的条件评估为 true 。如果在字符串中找不到给定的单词,则indexOf
会返回索引 -1 。
答案 2 :(得分:0)
密钥依赖于这两行
- This line
|
v
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);
if (foundAtPosition != -1) {
wroxCount++;
foundAtPosition++; <- And this line
}
算法正在移动字符串的位置:
例如:
var phrase = "The Wrox website is www.wrox.com." <- Iteration [1]
^
|_ First occurence at position [4] -> foundAtPosition++ = 5 -> wroxCount = 1
"The Wrox website is www.wrox.com." <- Iteration [2] -> The algorithm won't find the word because the `indexOf` function finds the index from position [5] til `phrase.length`.
^
|_ No more occurences, therefore, foundAtPosition = -1
结果: wroxCount === 1