Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 644
user1219627 Avatar asked Mar 03 '12 04:03

user1219627


2 Answers

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);
}
like image 121
rjz Avatar answered Nov 08 '22 17:11

rjz


I think what you want is a dictionary like structure (in JS it's called an object), eg { id => value}

In JS you can do something like this:

var myDict = { 'myId' : 'myValue' };
myDict[12] = 44; // from your example and this will be added to myDict
myDict[11] = 54;

for (var key in myDict) {
  console.log('key: ' + key + ', value: ' + myDict[key]);
}​

The output will be:

key: 11, value: 54

key: 12, value: 44

key: myId, value: myValue

like image 25
snjoetw Avatar answered Nov 08 '22 16:11

snjoetw