Dynamically creating array index

A

Andrew Poulos

If I have an array whose elements may or may not also be arrays and I’m
given a string that relates to an appropriate index in that array how do
I use that string as the index? For example, if I have an array that
looks like this:

myArray = [[0,1],[2,3]];

and a string that looks like:

str = “1_1”;

I can do this to the string:

foo = str.split(“_”); // foo now equals [“1”,”1”]

Then how can I use foo as an index? That is, something like

bar = myArray[foo]; // bar should now equal 3

and it's sibling

myArray[foo] = 1;

I've managed something using a FOR loop and eval but it seems such a
hack. And the problem is complicated by the fact that the array may have
as many levels of nested arrays as the user creates.


Andrew Poulos
 
J

Jonas Raoni

Andrew said:
myArray = [[0,1],[2,3]];
and a string that looks like:
str = “1_1”;
foo = str.split(“_”); // foo now equals [“1”,”1”]

Then how can I use foo as an index? That is, something like

bar = myArray[foo]; // bar should now equal 3

Is this what you're looking for?!

function navigate(o, path){
for(var x; (x = path.shift()) != undefined && o[x] != undefined; o = o[x]);
return o;
}

var x = [[0,1],[2,3]];

alert(navigate(x, [1, 1]));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,813
Messages
2,569,696
Members
45,479
Latest member
QFZErin313

Latest Threads

Top