-1

I'm looking at an array problem that I'm having trouble understanding how the values are being passed in the for loop:

var a = [ [ 1, 2 ], [ 3, 4] ];
a[ 1 ][ 1 ] = 5;
for ( var row = 0; row < a.length; row++ )
{
for ( var col = 0; col < a[ 0 ].length; col++ )
document.write( a[ row ][ col ] + " " );
document.write( "<br />" );

Running the program I see: 1 2 3 5

Are [ [ 1, 2 ], [ 3, 4] ] two separate arrays or one belonging to var a? I can see the first part of the array [ [ 1, 2 ] is being passed and printed, what happens to the second part?

***Sorry total newbie I'm just looking for a better explanation of arrays. Thanks you!

1
  • The initial array is an array with two elements. Each element is itself an array. Commented Jul 9, 2014 at 20:00

2 Answers 2

1

Look at it like this:

var a = [ [ 1, 2 ], [ 3, 4] ];

//means
a[0] = [1,2]
a[1] = [3,4]

//so
a[0][0] = 1 //first element in the first element
a[1][0] = 3 //first element in the second element
a[1][1] = 4 //second element in the second element

And so on.

At your second statement you changed the value of the second element of the second element.

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

1 Comment

Thank you @durbnpoisn. This is a great breakdown, very helpful in understanding how this is structured. Thanks for your time and input!
0

That would be a jagged array. Visually, you could think of it as:

[
    [1, 2],
    [3, 4]
]

Your second statement a[1][1] = 5 changes the second element of the second array (since arrays are zero-indexed).

The last blocks loop over the inner arrays, and then over the elements of those arrays so if you walk the array above like you are reading it, you get your output of:

1 2 3 5

1 Comment

Thanks @Justin Niessner this is helping me understand that second statement. Thank you for breaking it down and showing me how its affecting the values. Thanks!

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.