In this case, the outer loop runs first, setting the variable i to it's value, and while keeping that value constant, the inner loop runs setting j from 0 to 2 in order. When that's done, the outer loop sets i to its next value, and the inner loop runs again.
You can see from the logged statements the sequence these variables step through.
Why would you do this? It's not uncommon if you have a nested structure (like an array of arrays, or an array of objects) to want to do the same "loop" to each item in the top level collection.
This wouldn't have to be for loops - you could use forEach or while or any other "loop" construct, the key idea is that a variable set during the outer loop's execution is "fixed" while the inner loop is running, and the inner loop will run once for each value in the outer loop. In every case, put the inner loop inside the body of the outer loop - any place you would have put another expression you can add a loop.
Hi Collin,
I think you want to just put the "inner" loop inside the "outer" loop. For example
In this case, the outer loop runs first, setting the variable
i
to it's value, and while keeping that value constant, the inner loop runs settingj
from 0 to 2 in order. When that's done, the outer loop setsi
to its next value, and the inner loop runs again.You can see from the logged statements the sequence these variables step through.
Why would you do this? It's not uncommon if you have a nested structure (like an array of arrays, or an array of objects) to want to do the same "loop" to each item in the top level collection.
This wouldn't have to be
for
loops - you could use forEach or while or any other "loop" construct, the key idea is that a variable set during the outer loop's execution is "fixed" while the inner loop is running, and the inner loop will run once for each value in the outer loop. In every case, put the inner loop inside the body of the outer loop - any place you would have put another expression you can add a loop.Thanks very much, this helps a lot!