我的代码中是否存在无限循环?

时间:2011-08-27 17:45:58

标签: javascript

运行此网页时,我的网页崩溃了:

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;
    }
}

4 个答案:

答案 0 :(得分:2)

是的,当curstring位于cont时。在while循环中cont不会更改,因此cont.indexOf(curstring)始终为true

答案 1 :(得分:1)

可能,是的。

您的cont.indexOf()测试应该测试>= 0,因为在未找到该函数返回-1时,它会计算 true 并导致循环再次出现。

目前只有在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;
  }
}

答案 2 :(得分: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;
  }
}

答案 3 :(得分:0)

cont永远不会在循环中发生变化,所以如果cont.indexOf(curstring)为真,它将永远为真,你的程序会进入无限循环。