Chris Chris - 6 months ago 12
Javascript Question

JavaScript; n-dimensional array creation

In the process of building a JavaScript interpreter for a simple language, I've faced the following problem;

After parsing, we get an array of indices that specifies the element in an n-dimensional array to be modified. For instance, after parsing this:

a[1, 1, 1]


We get an array
[1, 1, 1]
. The language I'm working on doesn't have variable definitions, so variables get initialized on their first use. My goal is to be able to create this n-dimensional array so that I can place it in the variable table (in the example above, we'd need to create a 3-dimensional array).

The short question:

Is there a way to create an n-dimensional array in JavaScript without using
eval()
?

Answer

Untested:

function createNDimArray(dimensions) {
    if (dimensions.length > 0) {
        var dim = dimensions[0];
        var rest = dimensions.slice(1);
        var newArray = new Array();
        for (var i = 0; i < dim; i++) {
            newArray[i] = createNDimArray(rest);
        }
        return newArray;
     } else {
        return undefined;
     }
 }

Then createNDimArray([3, 2, 5]) should return a 3x2x5 array.

You can use a similar recursive procedure to access an element whose index is in an array:

function getElement(array, indices) {
    if (indices.length == 0) {
        return array;
    } else {
        return getElement(array[indices[0]], indices.slice(1));
    }
 }

Setting an element is similar, and left as an exercise for the reader.