Search code examples
javascriptarraysmultidimensional-array

Creating arrays in Javascript


I am little new to javascript and I am having alittle trouble wrapping my head around making a 2d (or maybe i might need a 3d) array in javascript.

I currently have 2 pieces of information i need to collect: an ID and a value so I created the following:

var myArray = [];

var id = 12;
var value = 44;

myArray[id]=value;

But I realized that this is not easy to loop through the array like a for loop so i was thinking of this:

myArray[myArray.length] = id;
myArray[myArray.length-1][id]=value;

I wanted to do this so that in a for loop i could get the ids and the values easily but the above only returns the value when i loop through it. Any suggestions on how to get this working or is there a better way to do this?

Thanks


Solution

  • Why not use an array of object hashes? This approach allows you to store multiple values in a key:value format:

    var myArray = [];
    var myElement = {
      id: 12,
      value: 44
    }
    
    myArray[0] = myElement;
    

    You could then loop through all of the elements in myArray like so:

    var i = 0,
        el;
    
    while (el = myArray[i++]) {
      alert(el.id + '=' + el.value);
    }