Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  150] [ 4]  / answers: 1 / hits: 31480  / 12 Years ago, sat, march 3, 2012, 12:00:00

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


More From » arrays

 Answers
14

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);
}

[#87072] Thursday, March 1, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andreguym

Total Points: 125
Total Questions: 112
Total Answers: 103

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;