[英]Javascript and for loops issue
Is something wrong with my code? 我的代码有问题吗? I was expecting my code:
我期待我的代码:
years=new Array();
for (i = 0; i < 5; ++i) {
for (j = 1; j < 13; ++j) {
player.push(Math.round( nestedData[i].value[j] ))
}
years.push(player)
}
console.log(years)
to print something like: 打印类似:
[array[12],array[12],array[12],array[12]]
but the result that i get is: 但我得到的结果是:
[array[60],array[60],array[60],array[60]]
Create a new player array inside the first for loop. 在第一个for循环内创建一个新的播放器数组。 The problem with your code is that the values were being pushed into the same array instance.
您的代码的问题在于,这些值已被推送到同一数组实例中。
var years = [];
for (i = 0; i < 5; ++i) {
var player = [];
for (j = 1; j < 13; ++j) {
player.push(Math.round( nestedData[i].value[j] ))
}
years.push(player)
}
console.log(years)
As an addition to the correct answer already, please use var
to declare your variables: 作为正确答案的补充,请使用
var
声明变量:
for (var i=0; i < 5; ++i) {
var player = [];
for (var j = 1; j < 13; ++j) {
...
Otherwise, it will use i
as a global variable, which could end poorly if you have two functions looping at the same time, eg: 否则,它将使用
i
作为全局变量,如果同时有两个函数循环,则结束效果可能很差,例如:
function loopone() {
//wouldn't expect this to be an infinite loop eh?
for (i=0; i < 100; i++) {
looptwo();
}
}
function looptwo() {
for (i=0; i < 10; i++) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.