Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...