The issue I am encountering is clearly depicted in the simplified code snippet below.
During the execution of the TestArrays function, the goal is to write a single item to each location in the multidimensional array. However, upon examining the layers in the console, it appears that every item exists in every layer. I am puzzled by this discrepancy and despite having successfully tackled similar problems in other programming languages, I am at a loss here.
It is worth noting that the layers where nothing was written indeed remain empty as expected. However, any writing to one address results in the presence of the item in all layers. To demonstrate this, I intentionally refrained from writing to the second address.
function ArrayND(initVal) {
/***********************************************************************************************
* The following function was sourced from Stack Overflow:
* https://stackoverflow.com/a/33362121
* It is responsible for creating the initial structure of the arrays
***********************************************************************************************/
var args = arguments;
var dims = arguments.length - 1
function ArrayCreate(cArr, dim) {
if (dim < dims) {
for (var i = 0; i < args[1 + dim]; i++) {
if (dim == dims - 1) cArr[i] = initVal
else cArr[i] = ArrayCreate([], dim + 1)
}
return cArr
}
}
return ArrayCreate([], 0)
}
function TestArray() {
let myArray = ArrayND("blank", 3, 8, 4, 1);
let emptyArray = [];
let innerArray;
let count = 1;
for (let outer = 1; outer <= 2; outer++) {
for (let middle = 1; middle <= 7; middle++) {
for (let inner = 1; inner <= 3; inner++) {
if (count != 2) {
myArray[outer][middle][inner].push(emptyArray);
let innerArray = [count, "Data1", "Data2"];
myArray[outer][middle][inner][1].push(innerArray);
}
count++;
}
}
}
for (let outer = 1; outer <= 2; outer++) {
for (let middle = 1; middle <= 7; middle++) {
for (let inner = 1; inner <= 3; inner++) {
console.log("Data at location: ".outer, middle, inner, "conatains: ", myArray[outer][middle][inner]);
}
}
}
}
TestArray();