0

I was trying to create a 3-dimensional array and couldn't find an easy way to do it.

array = [[[]]];

or

array = [][][];

or

array = []; array[] = []; array[][] = [];

would for example not work. (the console'd say the second array is 'undefined' and not an object, or for the second and third example give a parse error).

I cannot hard-code the information either, as I have no idea what the indexes and contents of the array are going to be (they are created 'on the fly' and depending on the input of a user. eg the first array might have the index 4192). I may have to create every array before assigning them, but it would be so much easier and faster if there's an easier way to define 3-dimensional arrays. (there'll be about 2 arrays, 25 subarrays and 800 subsubarrays total) every millisecond saves a life, so to say.

help please?

2 Answers 2

3

JavaScript is dynamically typed. Just store arrays in an array.

function loadRow() {
    return [1, 2, 3];
}

var array = [];
array.push(loadRow());
array.push(loadRow());
console.log(array[1][2]); // prints 3
Sign up to request clarification or add additional context in comments.

Comments

1

Since arrays in javascript aren't true arrays, there isn't really a multidimensional array. In javascript, you just have an arrays within an array. You can define the array statically like this:

var a = [
 [1,2,3],
 [4,5,6],
 [7,8,9]
];

Or dynamically like this:

var d = [];
var d_length = 10;
for (var i = 0;i<d_length;i++) {
  d[i] = [];
}

UPDATE

You could also use some helper functions:

function ensureDimensions(arr,i,j,k) {
  if(!arr[i]) {
    arr[i] = [];
  }
  if(!arr[i][j]) {
    arr[i][j] = [];
  } 
}

function getValue(arr,i,j,k) {
  ensureDimensions(i,j,k);
  return arr[i][j][k];
}

function setValue(arr,newVal,i,j,k) {
  ensureDimensions(i,j,k);
  arr[i][j][k] = newVal;
}

1 Comment

thanks, but as I mentioned I don't know what will be in the arrays or how long they will be.. this approach will sadly not help me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.