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
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With