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()?
Tested in Chrome:
Then
createNDimArray([3, 2, 5])returns a 3x2x5 array.You can use a similar recursive procedure to access an element whose index is in an array:
Setting an element is similar, and left as an exercise for the reader.