使用Javascript:困惑如何嵌套的for循环工作 [英] Javascript: confused about how nested for loops work
本文介绍了使用Javascript:困惑如何嵌套的for循环工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么嵌套的 for循环
的工作方式,他们在下面的例子做:
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);
}
}
在这个例子中我想到的console.log会给我下面的输出:
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?
编辑:
感谢您的答复!
推荐答案
您正在重新定义新时代
上的每一个循环,你输出对每列推控制台。
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);
返回: [04/11/10,86公斤,11年5月12日,90公斤,06/12/11,89公斤]
http://jsfiddle.net/niklasvh/SuEdt/
这篇关于使用Javascript:困惑如何嵌套的for循环工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文