Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Dynamically creating array index

Reply
Thread Tools

Dynamically creating array index

 
 
Andrew Poulos
Guest
Posts: n/a
 
      02-24-2006
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
 
Reply With Quote
 
 
 
 
Jonas Raoni
Guest
Posts: n/a
 
      02-24-2006
Andrew Poulos wrote:
> 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]));


--
Jonas Raoni Soares Silva
http://www.jsfromhell.com
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Making an array wrap, where last index + 1 = first index Shawn W_ Ruby 5 09-16-2009 02:45 PM
Templated array of templates specialized by array index npankey@gmail.com C++ 6 10-12-2008 03:20 PM
sorting index-15, index-9, index-110 "the human way"? Tomasz Chmielewski Perl Misc 4 03-04-2008 05:01 PM
Dynamically Creating a Select Index Gregc. Javascript 0 09-12-2006 04:19 AM
problem with index.html .(page is automatically gettin redirected to index.html) karthikeyavenkat Java 2 03-17-2005 10:01 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57