2011-06-04 57 views
5

为什么在路上嵌套for loops的工作,他们在下面的例子做:的Javascript:困惑如何嵌套的for循环工作

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


     } 

    } 

在这个例子中我会想到的console.log会给我下面输出:

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

不过,我居然得到这样的:

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

有人能够帮助我理解这一点吗?

编辑:

感谢您的所有答复!

回答

9

您正在每个单一循环中重新定义newTimes,并且您在每列推送中输出到控制台。

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

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

0

这样做:

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


     } 

    } 

要重新初始化新时代,通过每一次循环中。如果日志语句将读取

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

1

您的输出将是适当相反,你输出这是内环以外的初始化和每个内循环迭代增长的全新列表newTimes

1

问题出现在内循环的第二轮,它将第二个元素推入newTimes。无论如何,我不明白内循环的原因。你可以写得更简单:

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