开发者

Is there an infinite loop in my code?

My webpage crashes when I run this:

function replace()
{
    var str = document.getElementById('feeds');
    开发者_StackOverflow社区var cont = str.innerHTML;
    curstring = "twitter: ";
    while (cont.indexOf(curstring))
    {
        replaced = cont.replace(curstring,"TWIMG ");
        str.innerHTML = replaced;
    }
}


Yes, when curstring is in cont. In your while loop cont won't be changed, so cont.indexOf(curstring) will always be true.


Probably, yes.

Your cont.indexOf() test should test for >= 0, since on not-found that function returns -1, which evaluates true and will cause the loop to go around again.

It'll currently only terminate if cont starts with curstring.

Per other answers, you also need to overwrite cont inside the loop too.

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


Yes there is. You never reassign cont. Perhaps try this?

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


Yes cont never changes in the loop so if cont.indexOf(curstring) is true it will be true forever and your program goes into an infinite loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜