Can any body explain me the code below ? How does inner for loop works for that problem.
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]);
}
}
Can any body explain me the code below ? How does inner for loop works for that problem.
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]);
}
}
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.
Note: Backticks are not single quotes.
The first loop defines the value for variable ‘i’, and specifies to loop until ‘i’ is equal to the array length (loop through each array item):
The nested loop creates new variable ‘j’ and specifies to loop until ‘j’ is equal to the length of each nested array item (the array within the array):
The code then loops to log each item in the nested arrays to the console:
Dear Members,
Is there any website where I can understand my block of code step by step ?
I don’t know if it is step by step enough, but I really like this: http://pythontutor.com/javascript.html
Yes exactly. I was asking for this.
Thank you.
@camperextraordinaire I m not getting this what is j < arr[i].length used for ??
have confusion in second loop, cannot understand the code there.
The j
is used to loop over the elements of the sub-arrays
@TatTheFlame How nested loop works means if this condition fulfills for (var i=0; i < arr.length; i++) then it direct go to this loop for (var j=0; j < arr[i].length; j++) ?
and what is arr[i].length in it ?
literally it is blowing my head, hope this is normal for a newbie.
Try looking at the nested for loops with this: http://pythontutor.com/javascript.html
If you don’t get it yet we can try again to explain it