Don't Understand Nesting For Loops

Don't Understand Nesting For Loops
0

#1

Hi, so I completed the “Nesting For Loops” Challenge but don’t understand the challenge well and it seems that the challenge is now locked from comments. How does

for (var i=0; i < arr.length; i++) {
      for (var j=0; j < arr[i].length; j++) {
        console.log(arr[i][j]);

access arrays within:

   var arr = [
      [1,2], [3,4], [5,6]
    ];
    for (var i=0; i < arr.length; i++) {
      for (var j=0; j < arr[i].length; j++) {
        console.log(arr[i][j]);
      }
    }. 

Since we are using .length, aren’t we accessing the length (5) rather than the value of stored in the array? Also, if there are three different arrays within var arr, how is it that var i and var j can access all three arrays? Wouldn’t a third variable be needed? Thanks!


#2

arr.length and arr[i].length are not the same.

arr.length is 3 in the example below, because there are 3 elements. These 3 elements happen to be arrays also.

   var arr = [
      [1,2], [3,4], [5,6]
    ];

arr[i].length will depend upon what the value of i is in the outer for loop. Let’s say we are on the second iteration of the outer for loop, then i would be equal to 1 and would reference the 2nd element of arr which is [3, 4] which is an array itself. So if we are talking about arr[1].length, that value would be 2 because there are 2 elements in that array.


#3

Thanks! That makes a little more sense now.


#4

Thanks, this make lots of sense.