2011-08-27 45 views
0

當我運行此操作時,我的網頁崩潰:我的代碼中是否有無限循環?

function replace() 
{ 
    var str = document.getElementById('feeds'); 
    var cont = str.innerHTML; 
    curstring = "twitter: "; 
    while (cont.indexOf(curstring)) 
    { 
     replaced = cont.replace(curstring,"TWIMG "); 
     str.innerHTML = replaced; 
    } 
} 
+0

你試過用調試器試過嗎? – fvu

+1

您可能想要檢查您的TAB鍵是否正在工作......':p' –

回答

0

是的。你永遠不會重新分配續。也許試試這個?

function replace() 
{ 
    var str = document.getElementById('feeds'); 
    var cont = str.innerHTML; 
    curstring = "twitter: "; 
    while (cont.indexOf(curstring) != -1) 
    { 
    replaced = cont.replace(curstring,"TWIMG "); 
    str.innerHTML = replaced; 
    cont = str.innerHTML; 
    } 
} 
+0

完美!謝謝! –

2

是的,當curstringcont。在您的while迴路cont將不會更改,所以cont.indexOf(curstring)將永遠是true

1

也許,是的。

cont.indexOf()測試應該測試>= 0,由於未找到該函數返回-1,其評估真正並會導致循環再繞過去。

它現在只會終止,如果cont開始curstring

根據其他答案,您還需要在循環內覆蓋cont

function replace() { 
    var curstring = "twitter: "; 
    var str = document.getElementById('feeds'); 

    var cont = str.innerHTML; 
    var old = cont; 

    // NB: indexOf() returns -1 on failure, so you 
    //  must compare against that, 
    while (cont.indexOf(curstring) >= 0) { 
    cont = cont.replace(curstring, "TWIMG "); 
    } 

    // taken outside the loop so we don't modify the DOM 
    // over and over if the match is repeated - only update 
    // the DOM if the string got changed 
    if (cont !== old) { 
    str.innerHTML = cont; 
    } 
} 
+0

謝謝,它工作! –

+0

另外,不需要檢查> = 0,因爲如果它返回-1,它將評估爲false。 –

+0

@aerobit不,你錯了。 '!! - 1 === true' – Alnitak

0

cont從來沒有在循環會改變,所以如果cont.indexOf(curstring)是真的,那將是真正的永遠和你的程序進入一個無限循環。