Emilio Emilio - 2 months ago 8
Javascript Question

Storing value in a multidimensional array (Javascript)

What is the quickest way to store a value in an array at position, let's say, [30][1][0] ...

I tried

var myArray[30][1][0] = new Date();
but it won't work without doing
var myArray = []; myArray[30] = []; myArray[30][1] = [];
beforehand.

What am I doing wrong?

EDIT: My issue is that I don't know, first, if the variable array already exists and, second, if there's already a value at position, let's say, [29][2][15], which I wouldn't want to overwrite.

Answer

The correct way to do what you want would be:

var array = [[[new Date()]]];

However, the resulting multidimensional array will not have exactly 30 elements on the third dimension and 1 on the second, like you had in your original code. Not sure if that's going to be a problem for you.

When you do myArray[30][1][0], JavaScript is trying to access element 30 in the array myArray, but, since myArray variable was not initialized to anything yet, it has the value undefined. So your code is equivalent with:

var myArray;
myArray[30] = new Date();

This code is going to issue the error Cannot set property '30' of undefined.

Edit: If you want to make sure the array exists before assigning values and avoid overriding existing values, the most elegant way I can think of is:

// Store a value in the array, at index (posX, posY, posZ), only if
// that position in the array is currently empty
function storeDateNoOverride(theArray, posX, posY, posZ, date) {
    var theArray = theArray || [];
    theArray[posX] = theArray[posX] || [];
    theArray[posX][posY] = theArray[posX][posY] || [];
    theArray[posX][posY][posZ] = theArray[posX][posY][posZ] || date;
}

// If variable theArray doesn't have a value yet, assign it to a new array
var theArray = theArray || [];

storeDateNoOverride(theArray, 30, 1, 0, new Date());