Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
882 views
in Technique[技术] by (71.8m points)

arrays - Javascript: confused about how nested for loops work

Why do nested for loops work in the way that they do in the following example:

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


        }

    }

In this example I would have thought console.log would give me the following output:

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

However, I actually get this:

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

Is anyone able to help me understand this?

EDIT:

Thanks for all your responses!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are redefining newTimes on every single loop and you are outputting to the console on each column push.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...