Pergunta

Como posso construir um loop em JavaScript?

Foi útil?

Solução

Para loops

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...em loops

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

É uma má prática usar for...in loops para iterar sobre matrizes.Isso vai contra o ECMA 262 padrão e pode causar problemas quando atributos ou métodos não padrão são adicionados ao objeto Array, por exemplo.por Protótipo. (Graças a Chase Seibert por apontar isso nos comentários)

Enquanto faz loops

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

Outras dicas

Aqui está um exemplo de loop for:

Temos uma variedade de itens nós.

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

Você também pode considerar otimizar a velocidade do loop;ver http://www.robertnyman.com/2008/04/11/javascript-loop-performance/

Além dos loops integrados (while() ..., do ... while(), for() ...), existe uma estrutura de função de autochamada, também conhecida como recursão para criar um loop sem as três estruturas de loop integradas.

Considere o seguinte:

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

Escusado será dizer que esta estrutura é frequentemente usada em combinação com um valor de retorno, então este é um pequeno exemplo de como lidar com um valor que não está disponível no primeiro tempo, mas no final da recursão:

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

Um loop em JavaScript se parece com isto:

for (var = startvalue; var <= endvalue; var = var + increment) {
    // code to be executed
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top