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'
4
  • 2
    let library = lib2, Commented Jun 24, 2016 at 8:07
  • 1
    Why do you want to do this? If it's top level you can do window[library][index] Commented Jun 24, 2016 at 8:08
  • I need to do this in a function, and I do get the name as a parameter. Commented Jun 24, 2016 at 8:11
  • this.lib2[index] ? Commented Jun 24, 2016 at 8:13

2 Answers 2

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]);

Sign up to request clarification or add additional context in comments.

1 Comment

"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.
0

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

eval(library)[index];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.