Question

Comment puis-je créer une boucle en JavaScript ?

Était-ce utile?

La solution

Pour les boucles

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
}

Pour...en boucles

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

C'est une mauvaise pratique d'utiliser for...in boucles pour parcourir les tableaux.Cela va à l'encontre du ECMA 262 standard et peut causer des problèmes lorsque des attributs ou des méthodes non standard sont ajoutés à l'objet Array, par ex.par Prototype. (Grâce à Chase Seibert pour l'avoir souligné dans les commentaires)

Tandis que les boucles

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

Autres conseils

Voici un exemple de boucle for :

Nous avons une gamme d'articles nœuds.

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

Vous pouvez également envisager d'optimiser la vitesse de votre boucle ;voir http://www.robertnyman.com/2008/04/11/javascript-loop-performance/

Mis à part les boucles intégrées (while() ..., do ... while(), for() ...), il existe une structure de fonction auto-appelante, également connue sous le nom de récursivité pour créer une boucle sans les trois structures de boucle intégrées.

Considérer ce qui suit:

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

Inutile de dire que cette structure est souvent utilisée en combinaison avec une valeur de retour, voici donc un petit exemple de la façon de gérer une valeur qui n'est pas disponible au début, mais à la fin de la récursion :

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

Une boucle en JavaScript ressemble à ceci :

for (var = startvalue; var <= endvalue; var = var + increment) {
    // code to be executed
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top