I have a situation where I wish to build an array that can be accessed via:
myArray['Foo'].push(myObj);
But I do not know how to create it from scratch. From what I had read I thought maybe the following would do it:
var myArray = new Array(new Array());
Problem is that it only lets me use integers to reference the myArray[]. If I ignore this limitation and try the following it errors saying it doesn't have .push():
myArray[i].push(myObj);
I presume this is because myArray[i] is returning a string?
So my question is, how do I build a dynamic array where I reference the first dimension using strings and can then push and pop on the second dimension? Also if I take this approach, can I use push and pop for adding the string to the first dimension?
I thought about this a bit more before and wrote some code I thought may work, which it does.
var myArray = new Object();
var myObj = new Object();
var myObj2 = new Object();
var myObj3 = new Object();
myObj.name = "Harry";
myObj2.name = "Curly";
myObj3.name = "Moe";
myArray["first"] = new Array()
myArray["first"].push(myObj);
myArray["first"].push(myObj2);
myArray["first"].push(myObj3);
myArray["second"] = new Array()
myArray["second"].push(myObj2);
myArray["third"] = new Array()
myArray["third"].push(myObj3);
iterate(myArray, "first");
iterate(myArray, "second");
iterate(myArray, "third");
function iterate(array, name) {
for(i = 0, l = myArray[name].length; i < l; i++) {
console.log(" " + name + ": " + i + " value " + myArray[name][i].name);
}
}
Is the above the correct way to go about it?
I'm sure I've got some terminology problems with the above, let me know and I'll edit it so it's correct.