1

How can I select an array variable by its name?

This is what I'm doing so far to get the content in a dynamic way:

const lib1 = ['banana', 'apple'],
      lib2 = ['audi', 'bmw'];
let   index = 1;

lib1[index] // result: apple

Now I need to select the array-variable also dynamical:

let library = 'lib2',
    index = 1;

library[index] // wrong - but should result 'bmw'
user3142695
  • 15,844
  • 47
  • 176
  • 332

2 Answers2

3

You could change the data structure a bit and access then with a key.

var lib1 = ['banana', 'apple'],
    lib2 = ['audi', 'bmw'],
    object = {lib1, lib2},
    index = 1,
    library = 'lib2';

console.log(object[library][index]);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • *"Advantage: it is not restricted to the global space"* - Local *or* global it is best to use an appropriate data structure for the job rather than separate variables, which in this case means organising each `libX` array within a single object just like you've shown. – nnnnnn Jun 24 '16 at 08:25
0

You want to use variable as a execute code ,if so try with eval()

eval(library)[index];
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52