It's just that I'm learning for loops in Javascript but I got a for loop nested within another and I don't fully understand how this works. According to what I saw in a result, it is that one is multiplied by another (or something similar) but the truth is that I do not understand how it is multiplied or how this code works.
If I don't formulate my question correctly, tell me? Please.
Thanks in advance.
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]);
}
}
It's something like this:
Remember that JavaScript arrays start traversing from index zero (0), this being the first position.
...Continuity edition
arr.length // Como variable arr es un arreglo, todos los arreglos contienen en su naturalidad esta propiedad lenth; y esta propiedad cuenta el total de datos que almacena dicho arreglo
We explain;
So when the code says:
var i=0; i<arr.length; i++
means; we start a variable calledi
in its value0
, the cycle will continue only as long asi
it is less thanarr.length
(the total of the values that arr contains; 3 for this example) and finally we increase the value ofi
by 1 unit.Basically what you do with this code is to go through a multidimensional array, that is, an array
by declaring var arr you have a 3x2 matrix
With the first for loop you loop through the rows so it would be
arr.length
= 3, with the second for loop you loop through the columns so it would bearr[i].length
equal to 2.Once you have i and j you can access the positions of the array. You can check this by doing a
Since those values are the ones that are replaced by i and j.