I want to fill a 2d array, and I have this code in javascript:
n=2; //rows
m=3; //columns
z=0;
array1=[];
for(i=0;i<n;i++){
for(j=0;j<m;j++){
array1[i]=[];
array1[i][j] = z;
console.log(i+","+j+"="+z); //debug
z++;
}
}
console.log(array1);
But instead of getting this expected result;
[[0, 1, 2], [3, 4, 5]]
I get:
[[undefined, undefined, 2], [undefined, undefined, 5]]
why!? I don't understand why I am getting undefined for all the items in each "inner" array, except the last one which is correct (here, the 2 and 5).
I made a debug step logging each i,j pair and the assigned z value, and i DO get the correct pair-values each time (i,j=z):
0,0=0
0,1=1
0,2=2
1,0=3
1,1=4
1,2=5
so, I think I am correctly filling the array using arr[i][j]=z each time, so why does it get undefineds for those cases?
I also tried using the arr=new Array() instead of arr=[] syntax in both cases, but with the same result.
Any ideas? I'm almost sure it will be a trivial error, but I can't find what is wrong!.
Thanks.