2008-09-09 9 views
5

¿Cómo puedo crear un bucle en JavaScript?¿Cómo construyo un bucle en JavaScript?

+0

Alguien está jugando con SO, bajando un montón de cosas, parece ... –

+0

ahh. Bueno, supongo que mi diatriba sobre la voz de usuario sobre esto saltó el arma un poco entonces. – UnkwnTech

+0

Estas preguntas fueron alentadas, en los podcasts, porque ayudarán al sitio en general, porque las personas que busquen esto en la red lo encontrarán y/o lo ayudarán con las estadísticas de Google. – UnkwnTech

Respuesta

24

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 de utilizar for...in bucles a itterate sobre matrices. Va en contra del estándar ECMA 262 y puede causar problemas cuando se agregan atributos o métodos no estándar al objeto Array, p. por Prototype. (Gracias a Chase Seibert por señalar esto en los comentarios)

bucles while

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

No debe usar para ... in para recorrer las matrices. Esto causará problemas con Prototype. Ver http://www.prototypejs.org/api/array –

+2

El problema con los bucles for-in puede evitarse si comprueba con hasOwnProperty: if (! Things.hasOwnProperty (i)) {continue; } –

-1

Un bucle en JavaScript se parece a esto:

for (var = startvalue; var <= endvalue; var = var + increment) { 
    // code to be executed 
} 
1

Aquí está un ejemplo de un bucle for:

Tenemos una gran variedad de artículos nodos.

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

Aparte formar los bucles construir-en (while() ..., do ... while(), for() ...), hay una estructura de la función de auto llamado, también conocido como recursividad para crear un bucle sin las tres estructuras de bucle construir-en.

considerar 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();

Ni que decir tiene que esta estructura se utiliza a menudo en combinación con un valor de retorno, por lo que este es un pequeño ejemplo de cómo lidiar con valor que es no en el primer tiempo disponible, pero 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));

Cuestiones relacionadas