0

Working with the following code:

Array0 = ['a', 'b', 'c'];
Array1 = ['c', 'd', 'e'];
Array2 = ['x', 'a', 'd'];
...

/*
doStuff() is a recursive function whose argument is an abitrary length array
containing an arbitrary list of array names
e.g., anArr = ['Array1', 'Array0', 'Array1', 'Array2', ...]
*/

function doStuff(anArr) {

    for(i=0; i<anArr.length; i++)   {

      switch(anArr[i])  {
      case('Array0')    :   Array0.myMethod(); break;
      case('Array1')    :   Array1.myMethod(); break;
      case('Array2')    :   Array2.myMethod(); break;
      }

    }
}

Is there a way to replace the switch() block with a single statement:

<<array referenced by 'someArray'>>.aMethod()   //or
function aFunction (<<array referenced by 'someArray'>>){}

Plain Javascript, please - no jquery or other library. Thanks

grymlord
  • 42
  • 5

2 Answers2

4

Use an object in the first place.

var foo = {
  Array0 : ['a', 'b', 'c'];
  Array1 : ['c', 'd', 'e'];
  Array2 : ['x', 'a', 'd'];
}

Then you can:

foo[anArr[i]].myMethod();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • won't work for my app, because an array is allowed to be a member of another array: `var foo = { A0 : ['a', 'b', 'c'], A1 : ['c', 'd', 'e'], A2 : ['x', 'a', 'd', A0]` dies. } – grymlord Jan 22 '15 at 18:48
  • If you need to reference part of an object from another part of it, then just define all the parts in variables first, and then put them together into the object afterwards. – Quentin Jan 22 '15 at 19:43
3

You can store the actual arrays in the array...

Array0 = ['a', 'b', 'c'];
Array1 = ['c', 'd', 'e'];
Array2 = ['x', 'a', 'd'];

var anArr = [Array0, Array1, Array2];
for(i=0; i<anArr.length; i++) {
    anArr[i].myMethod();
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • This won't work in my application, because arrays may have arrays whose members are only defined subsequently. - `Array0 =['a', Array1]; Array1 = ['b', 'c'];`, which would throw an undefined variable error That's not apparent from the code I posted. Sorry. – grymlord Jan 22 '15 at 16:06
  • @grymlord — You'd get that problem with your existing code anyway. – Quentin Jan 22 '15 at 19:44