Getting array value using a var as index

A

Andrew Poulos

Say I have a multi-dimensional array and I have an index (held in a
variable) that is itself an array, how do I get the array element that
is referred to. For example,

myArray = [1, [2, [3, 4]], 5];
ind = [1,1,1]; // it's pointing to the value 4

I've tried unsuccessfully
myArray[ind];
myArray.ind;
myArray.eval(ind);

fGetValue = function(ind) {
var el;
for (var i = 0; i<ind.length;i++) {
el = myArray[ind];
// ??? a mess of spaghetti code
}
return el;
}


Andrew Poulos
 
U

Ulrik Skovenborg

Andrew said:
Say I have a multi-dimensional array and I have an index (held in a
variable) that is itself an array, how do I get the array element that
is referred to. For example,

myArray = [1, [2, [3, 4]], 5];
ind = [1,1,1]; // it's pointing to the value 4

I've tried unsuccessfully
myArray[ind];
myArray.ind;
myArray.eval(ind);

fGetValue = function(ind) {
var el;
for (var i = 0; i<ind.length;i++) {
el = myArray[ind];
// ??? a mess of spaghetti code
}
return el;
}


We could use your fGetValue-function with a few changes:
myArray = [1, [2, [3, 4]], 5];
ind = [1,1,1]; // it's pointing to the value 4
fGetValue = function(ind) {
var el;
el = myArray;
for (var i = 0; i<ind.length;i++) {
if (el) {el = el[ind];}
else {el = null;break;}
}
return el;
}
alert(fGetValue(ind));

Now everytime the loop runs it goes one step deeper into the
myArray-array (which is currently stored in he el-variable) though it
will stop if you goes to a index in the array that does not exist (and
it will return null). One exception is when you use ind = [1,1,2]; it
will return undefined because the "sub-array" it points to exist but not
the value.
 

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

Forum statistics

Threads
473,785
Messages
2,569,624
Members
45,319
Latest member
LorenFlann

Latest Threads

Top