In my function, I defined two arrays, the first (array1) has a pre-initialized length. I added a second array (array2) just for testing, because I thought the first one behaved strangely.
My code is:
function test(n = 3) { array1 = new Array(n).fill(new Array(n)); array2 = [ [undefined, undefined, undefined], [undefined, undefined, undefined], [undefined, undefined, undefined] ]; document.getElementById("output").innerHTML = JSON.stringify(array1) + " (array 1) <br/>" + JSON.stringify(array2) + " (array 2)<br/><br/><hr/>"; for (i = 0; i < n; i++) { array1[i][0] = i; array2[i][0] = i; } document.getElementById("output").innerHTML += JSON.stringify(array1) + " (array 1) <br/>" + JSON.stringify(array2) + " (array 2)<br/><br/><hr/>"; }
<button onclick="test();">Press to test</button> <br/><br/> <div id="output"></div>
In a for loop, I'm trying to change the first value of the second dimensions. It should output [[0, undefined, undefined], [1, undefined, undefined], [2, undefined, undefined]] , as the second array does.
My questions are: why is this happening? And how can I make a pre-initialized array of length n in both dimensions that behaves like a second array?
Sacha source share