I'm currently working on a function that generates a 10 by 10 array filled with random D's and E's. Below is the code snippet:
function generateTenByTenArray(){
var outerArray = [];
var innerArray = [];
for(var i = 0; i < 10; i++){
for(var j = 0; j < 10; j++){
if((Math.floor(Math.random() *10) +1) % 2 == 0){
innerArray[j] = ("D");
} else {
innerArray[j] = ("E");
}
}
outerArray[i] = innerArray;
}
return outerArray;
}
However, when I run this function, I noticed that all the 10 arrays have the same values. It seems like the values in innerArray
are being overwritten. Can someone explain why the new values are updating the arrays in outerArray
?
If I include innerArray = []
right after outerArray[i] = innerArray
, the function works as expected. I'm curious as to why this redeclaration of innerArray
to an empty array fixes the issue. Does it have something to do with accessing a new memory allocation?
Thank you for your assistance in advance!