David David - 8 months ago 36
Javascript Question

Write name of array on the go from name + variable

I have such array component which prints out Good.


But now I want to print it out like this

var ccc='componentA';

But it's not working unfortunately :(
Where is my mistake ?

Answer Source

Although it's not recommended, you can do this in Javascript without having to use eval(). Since global variables are descendants of the window object, you can access them like this:

var ccc='componentA';
console.log(window['nameA_' + ccc]['abc'].aaa);

But it's probably better practice to use objects / arrays instead of using this method.