1

I'm looking to access a variable by using a variable name dynamically computed at runtime. Example code:

var firstSecond = ['a', 'b', 'c'];
var tempDatabase = 'first';
var tempTable = 'Second';
var copyArray = MAGIC(tempDatabase + tempTable);

copyArray should be the array: ['a', 'b', 'c']. Is there a way to achieve this?

Cactus
  • 27,075
  • 9
  • 69
  • 149
jarsushi
  • 57
  • 5
  • It's unclear what you're asking. `copyArray` is equal to `"firstSecond"` not an array. – David G Mar 04 '16 at 01:54
  • 1
    No. You cannot access local variables by name in JavaScript, except by evil. And you cannot copy arrays by assignment. This seems like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem): what are you actually trying to do? – Amadan Mar 04 '16 at 01:55
  • Have you checked out http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript ? – General_Twyckenham Mar 04 '16 at 02:04
  • `MAGIC = eval`, but you really should not. Store all the possible arrays in an object, and reference them by a dynamic property name. – Bergi Mar 04 '16 at 02:04

1 Answers1

1

You can use an object:

var o = {firstSecond: ['a', 'b', 'c']}
var tempDatabase = 'first';
var tempTable = 'Second';
var copyArray = o[tempDatabase + tempTable];

document.write(copyArray)

https://jsfiddle.net/pdt3sse7/

Julien
  • 833
  • 8
  • 20