Domanda

Come posso creare un ciclo in JavaScript?

È stato utile?

Soluzione

Per i loop

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
}

Per...in loop

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

È una cattiva pratica da usare for...in loop per scorrere gli array.Va contro il ECMA 262 standard e può causare problemi quando attributi o metodi non standard vengono aggiunti all'oggetto Array, ad es.di Prototipo. (Grazie a Insegui Seibert per averlo sottolineato nei commenti)

Mentre i cicli

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

Altri suggerimenti

Ecco un esempio di ciclo for:

Abbiamo una vasta gamma di articoli nodi.

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

Potresti anche considerare di ottimizzare la velocità del loop;Vedere http://www.robertnyman.com/2008/04/11/javascript-loop-performance/

A parte i loop incorporati (while() ..., do ... while(), for() ...), esiste una struttura di funzione di autochiamata, nota anche come ricorsione per creare un loop senza le tre strutture di loop integrate.

Considera quanto segue:

// 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 dire che questa struttura viene spesso utilizzata in combinazione con un valore restituito, quindi questo è un piccolo esempio di come gestire un valore che non è disponibile nel primo momento, ma alla fine della ricorsione:

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 ciclo in JavaScript assomiglia a questo:

for (var = startvalue; var <= endvalue; var = var + increment) {
    // code to be executed
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top