0

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.

2
  • 1
    You'd probably spot the error faster if you used meaningful variable names, such as row, rows, column, columns, and counter; instead of i, n, j, m, and z. Commented Jan 24, 2013 at 23:21
  • @PatrickMcElhaney this is an excellent suggestion Commented Jan 25, 2013 at 0:27

2 Answers 2

7

You are reinitializing the empty array in every loop iteration:

array1[i]=[];

When you should only be doing this once per value of i. Move the initialization out of the inner-most loop.

Sign up to request clarification or add additional context in comments.

1 Comment

OH! I know it would be trivial, now I fell dumb. Thanks!
0

Here is how it should be

n=2; //rows
m=3; //columns
z=0;
array1=[];
for(i=0;i<n;i++){
    array1[i]=[];
    for(j=0;j<m;j++){
        array1[i].push(z); // Here is my change
        console.log(i+","+j+"="+z); //debug
        z++;
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.