Tell us what’s happening:
I am having issues trying to understand this concept of multi-dimensional arrays and how they function. Specifically this statement that outputs the contents through console. This is what I know so far:
- When everything is ran, the contents of the array are logged to console.
- The outer for statement will focus on the outside array.
- The inner for statement will focus on the sub arrays.
- When the outer for statement is ran and the condition is met, the next one starts.
- When the inner for statement runs the condition is checked, met, and the inner code is ran.
- So, with the inner for statements first loop, we get console.log(arr[0][0]), printing 1 to the console from the array and j is incremented to 1.
- Then, j is checked with it’s condition, met, and the inner code is ran again console.log(arr[0][1]), printing 2 to the console.
- So, j’s condition is still not met (j which is 1 < arr[0].length which is 2), and j is still not greater than the length of the sub array (arr[i].length) which is 2, so it loops again.
- Now, with the second loop j is now 2, and now the condition is met because 2 is not less then 2, and the outer for statement is ran.
Now, here is where my issue begins. If the outer loop is now 1 due to the increment, and we jump back down to the inner for statement j is still 2.
If we continue to loop with the inner loop, j will continue to rise above 2, and it will not be able to pick up the other sub array.
Why can I not understand this? Does the inner-loop reset after it’s condition is met? If so, why is this not specified ANYWHERE on the curriculum.
Outside Array Order: 0 1 2
[
[1, 2], Inner Array Order: 0 1
[3, 4], Inner Array Order: 0 1
[5, 6] Inner Array Order: 0 1
]
Your code so far
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]);
}
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops