I am trying to understand how nested loops work with multidimensional arrays in JavaScipt, and I am a bit stuck at one point. Using stock example
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]);
}
}
This outputs 1 2 3 4 5 6, as I expected. However, if I add numbers to the end of the external array:
var arr = [[1,2], [3,4], [5,6], 7, 8];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
Am I still getting the same result 1 2 3 4 5 6 ?? I am confused why 7 and 8 are not caught in a loop. Interestingly, if I use strings instead:
var arr = [["a","b"], ["c","d"], "y", "z"];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
The conclusion is bcdyz, as I expected. Why does it behave differently for strings?
source
share