2011-06-04 5 views
5

¿Por qué anidada for loops el trabajo de la manera que lo hacen en el siguiente ejemplo:Javascript: confundido acerca de cómo funcionan los bucles anidados

var times = [ 
      ["04/11/10", "86kg"], 
      ["05/12/11", "90kg"], 
      ["06/12/11", "89kg"] 
]; 

for (var i = 0; i < times.length; i++) { 
     var newTimes = []; 
     for(var x = 0; x < times[i].length; x++) { 
      newTimes.push(times[i][x]); 
      console.log(newTimes); 


     } 

    } 

En este ejemplo Tendría console.log pensado me daría el siguiente salida:

["04/11/10"] 
["86kg"] 
["05/12/11"] 
["90kg"] 
["06/12/11"] 
["89kg"] 

Sin embargo, en realidad conseguir esto:

["04/11/10"] 
["04/11/10", "86kg"] 
["05/12/11"] 
["05/12/11", "90kg"] 
["06/12/11"] 
["06/12/11", "89kg"] 

¿Alguien puede ayudarme a entender esto?

EDIT:

Gracias por todas sus respuestas!

Respuesta

9

Está redefiniendo newTimes en cada bucle y está enviando a la consola en cada impulso de columna.

var times = [ 
      ["04/11/10", "86kg"], 
      ["05/12/11", "90kg"], 
      ["06/12/11", "89kg"] 
]; 
var newTimes = []; 
for (var i = 0; i < times.length; i++) {  
     for(var x = 0; x < times[i].length; x++) { 
      newTimes.push(times[i][x]); 
     } 
    } 
    console.log(newTimes); 

Devuelve: ["04/11/10", "86kg", "05/12/11", "90kg", "06/12/11", "89kg"] http://jsfiddle.net/niklasvh/SuEdt/

0

hacer esto: NewTimes

var newTimes = []; 
for (var i = 0; i < times.length; i++) { 
     for(var x = 0; x < times[i].length; x++) { 
      newTimes.push(times[i][x]); 
      console.log(newTimes); 


     } 

    } 

está volviendo a la inicialización de cada iteración del bucle.

1

salida que sería apropiado si la declaración de registro leería

console.log(times[i][x]); 

En su lugar, la salida de su nueva lista completa newTimes que es inicializado fuera del bucle interno y crece con cada iteración del bucle interno.

1

El problema está en la segunda vuelta del bucle interno, donde empuja el segundo elemento en newTimes. De todos modos, no entiendo la razón del ciclo interno. Puede escribir mucho más simple:

var times = [ 
      ["04/11/10", "86kg"], 
      ["05/12/11", "90kg"], 
      ["06/12/11", "89kg"] 
]; 

for (var i = 0; i < times.length; i++) { 
    console.log(time[i][0]); 
    console.log(time[i][1]); 
} 
3
// remember that the increment of the counter variable 
// is always executed after each run of a loop 


for (var i = 0; i < n; i++) { 
    // some statement(s) to do something.. 

     // initializes child-loop counter in the first run of the parent-loop 
     // resets child-loop counter in all following runs of the parent-loop 
     // while i is greater than 0 and lower than n 

    for (var j = 0; j < p; j++) { 
     // some statement(s) to do something.. 

      // initializes grandchild-loop counter in the first run of the child-loop 
      // resets grandchild-loop counter in all following runs of the child-loop 
      // while j is greater than 0 and lower than p 

     for (var k = 0; k < q; k++) { 
      // some statement(s) to do something.. 
      // or add more internal loop-nestings if you like.. 
     } 
    } 
} 

// if the counter variables of the descendent-loops were set before the loop-nesting, 
// the inner loops would only run once, because the counter would keep the value 
// of the abortion condition after the loop is finished 
Cuestiones relacionadas