By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,628 Members | 1,692 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,628 IT Pros & Developers. It's quick & easy.

Getting array value using a var as index

P: n/a
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[i]];
// ??? a mess of spaghetti code
}
return el;
}
Andrew Poulos
Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Andrew Poulos wrote:
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[i]];
// ??? 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[i]];}
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.
Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.