簡體   English   中英

我不明白為什么這個循環不是無限的

[英]I don't understand why is this loop not infinite

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

我不明白為什么這個循環不是無限的

如果不傳遞foundAtPosition的第二個參數,它將是無限的

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

但是,由於您傳遞了此參數,因此第二次以后,它將從(在foundAtPosition索引之后)開始foundAtPosition ,最終它將具有-1

while循環執行while條件評估為true 當在字符串中找不到給定的單詞時, indexOf返回索引-1

關鍵在於這兩行

- 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

資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM