要停止循环,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");

最佳答案

关键在于这两行

- This line
|
v
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);

if (foundAtPosition != -1) {
    wroxCount++;
    foundAtPosition++; <- And this line
}


该算法正在遍历您的String的位置:

例如:

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

资源资源


String.prototype.indexOf()

09-30 19:00
查看更多