Dynamically add elements to 2-D array

<>

This question already has an answer here:

Answers


What John Hartsock probably meant (in his answer) was:

var my2DArray = [], i, j;

for(i = 0; i < 5; i++){
  my2DArray.push([]);
  for(j = 0; j < 5; j++){
    my2DArray[i].push("Array Position " + i + ", " + j);
  }
}

alert(my2DArray[0][0]); //will alert "Array Postion 0, 0"
alert(my2DArray[1][4]); //will alert "Array Postion 1, 4"

Working jsfiddle demo here.

OR using a temporary reference to each new 'sub-array' (can be faster):

var my2DArray = [], i, j, tempRef;

for(i = 0; i < 5; i++){
  tempRef = my2DArray[i] = [];
  for(j = 0; j < 5; j++){
    tempRef.push("Array Position " + i + ", " + j);
  } 
}

alert(my2DArray[0][0]); //will alert "Array Postion 0, 0"
alert(my2DArray[1][4]); //will alert "Array Postion 1, 4"

Working jsfiddle demo here.

Explanation:

One normally uses var arr=[]; to create an array and arr.push(/*content*/); to add a new array-item to the end of the array (so it is essentially the same as arr[arr.length]=/*content*/;).

Thus, if you have an array (my2DArray), then you add new arrays (since arrays are passed by reference, not copied) to your main/root array: my2DArray.push([]); to make my2DArray[my2DArray.length] reference this new array (and once this array exists, you can do stuff with it: my2DArray[index][sub_index]).

So, say you have just one loop, then you could also add a complete new array with a single push: my2DArray.push([0,1,2,3]);

Put differently, (using what is explained above,) this single line will create exactly the 2d array you gave as example in your question:

for(var array2d=[], i=0; i<4; array2d[i++]=[0, 1, 2, 3]);
alert(  array2d[2][1]  );  //returns '1'

jsfiddle demo here.

By the way, technically there aren't even arrays in javascript, just fancy objects with some special features (excellent explanation here: https://stackoverflow.com/a/2891043/588079)


Need Your Help

Capture Windows screen with ffmpeg

windows ffmpeg screen-capture

The ffmpeg is cross-platform and very powerful software to handle video/audio or to stream it.

Encoding and updating bits with a checkbox - Succinctest method

javascript jquery html coldfusion

Is it possible to store a value (ie "1" or "0") in a checkbox input so that a secondary, hidden input isn't required to encode the checked status of it?