I am working on a problem that outputs its results into a 2D array, adding one to each element as it goes.
I simplified the code down as far as I could to create a test case. If I fill the array as a I go, as follows:
var a = [[], [], [] ,[] ,[], []];
var d1, d2;
for (d1 = 0; d1 < 6; d1++) {
for (d2 = 0; d2 < 6; d2++) {
a[d1][d2] = (a[d1][d2]) ? (a[d1][d2]) + 1 : 1;
}
}
I get a 2D array where all the values are 1. However, if I prefill the array using array.prototype.fill() as follows:
var a = new Array(6).fill(new Array(6).fill(0));
var d1, d2;
for (d1 = 0; d1 < 6; d1++) {
for (d2 = 0; d2 < 6; d2++) {
a[d1][d2] += 1;
}
}
I get a 2D array full of 6s. Even if I replace a[d1][d2] += 1
with the old a[d1][d2] = (a[d1][d2]) ? (a[d1][d2]) + 1 : 1;
, (which should still work since both 0 and undefined are falsy) I still get 6s.
As far as I can tell, my code should just loop through each element and add one to the previous value. It shouldn't touch any element more than once, so they should all be 1s. Whether I fill the array ahead of time or not shouldn't matter.
Where is the failure in my understanding?