简体   繁体   中英

I don't understand why is this loop not infinite

To stop the loop foundAtPosition needs to be equal to -1 how is that ?

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");

i don't understand why is this loop not infinit

It will be infinite if you don't pass the second parameter foundAtPosition

foundAtPosition = myString.indexOf("Wrox", foundAtPosition);

But since you passed this parameter, second time onwards it will look from (after this foundAtPosition index) and eventually it will have -1

while loop is executing while is condition evaluated as true . indexOf returns index -1 when given word is not found in string.

The key relies on these two lines

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

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

The algorithm is moving through the positions of your String:

For example:

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

Result: wroxCount === 1

Resource

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM