¿Hay un bucle infinito en mi código?

My webpage crashes when I run this:

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

preguntado el 27 de agosto de 11 a las 17:08

did you try stepping through it with a debugger? -

You might want to check if your TAB key is working... :p -

4 Respuestas

Si, cuando curstring es en cont. En tus while loops cont won't be changed, so cont.indexOf(curstring) siempre será true.

Respondido 27 ago 11, 21:08

Probablemente si.

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

It'll currently only terminate if cont comienza con 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;
  }
}

Respondido 28 ago 11, 00:08

Also, there is no need to check for >=0 because if it returns -1 it will evaluate as false. - Ari Lotter

Sí, >= 0 is correct. But while (a.indexOf(b)) { ... } no lo es, porque -1no evaluate as false. - Alnitak

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

Respondido 27 ago 11, 21:08

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.

Respondido 27 ago 11, 21:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.