Pregunta

¿Cómo puedo crear un bucle en JavaScript?

¿Fue útil?

Solución

Para bucles

for (i = startValue; i <= endValue; i++) {
    // Before the loop: i is set to startValue
    // After each iteration of the loop: i++ is executed
    // The loop continues as long as i <= endValue is true
}

Para... en bucles

for (i in things) {
    // If things is an array, i will usually contain the array keys *not advised*
    // If things is an object, i will contain the member names
    // Either way, access values using: things[i]
}

Es una mala práctica utilizar for...in bucles para iterar sobre matrices.Va en contra del ECMA 262 estándar y puede causar problemas cuando se agregan atributos o métodos no estándar al objeto Array, p.por Prototipo. (Gracias a Chase Seibert por señalar esto en los comentarios)

mientras bucles

while (myCondition) {
    // The loop will continue until myCondition is false
}

Otros consejos

A continuación se muestra un ejemplo de un bucle for:

Tenemos una variedad de artículos. nodos.

for(var i = 0; i< nodes.length; i++){
    var node = nodes[i];
    alert(node);
}

También podrías considerar optimizar la velocidad de tu bucle;ver http://www.robertnyman.com/2008/04/11/javascript-loop-performance/

Aparte de los bucles incorporados (while() ..., do ... while(), for() ...), existe una estructura de función de autollamada, también conocida como recursividad para crear un bucle sin las tres estructuras de bucle integradas.

Considera lo siguiente:

// set the initial value
var loopCounter = 3;

// the body of the loop
function loop() {

    // this is only to show something, done in the loop
    document.write(loopCounter + '<br>');

    // decrease the loopCounter, to prevent running forever
    loopCounter--;

    // test loopCounter and if truthy call loop() again 
    loopCounter && loop();
}

// invoke the loop
loop();

No hace falta decir que esta estructura se usa a menudo en combinación con un valor de retorno, por lo que este es un pequeño ejemplo de cómo lidiar con un valor que no está disponible la primera vez, sino al final de la recursividad:

function f(n) {
    // return values for 3 to 1
    //       n   -n  ~-n   !~-n   +!~-n   return
    // conv int neg bitnot  not  number 
    //       3   -3   2    false    0    3 * f(2)
    //       2   -2   1    false    0    2 * f(1)
    //       1   -1   0     true    1        1
    // so it takes a positive integer and do some conversion like changed sign, apply
    // bitwise not, do logical not and cast it to number. if this value is then
    // truthy, then return the value. if not, then return the product of the given
    // value and the return value of the call with the decreased number
    return +!~-n || n * f(n - 1);
}

document.write(f(7));

Un bucle en JavaScript se ve así:

for (var = startvalue; var <= endvalue; var = var + increment) {
    // code to be executed
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top