Getting array value using a var as index

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew Poulos

    Getting array value using a var as index

    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(in d);

    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
  • Ulrik Skovenborg

    #2
    Re: Getting array value using a var as index

    Andrew Poulos wrote:[color=blue]
    > 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(in d);
    >
    > fGetValue = function(ind) {
    > var el;
    > for (var i = 0; i<ind.length;i+ +) {
    > el = myArray[ind[i]];
    > // ??? a mess of spaghetti code
    > }
    > return el;
    > }[/color]

    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.


    Comment

    Working...