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

Is there an infinite loop in my code?

本文关键字:存在 无限循环 是否 代码 我的      更新时间:2023-09-26

当我运行这个时,我的网页崩溃了:

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

是,当curstringcont中时。在你的while循环cont不会改变,所以cont.indexOf(curstring)将永远是true

可能是的。

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

有。你从不重新分配内容,也许试试这个?

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

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