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?

4
  • It's unclear what you're asking. copyArray is equal to "firstSecond" not an array. Commented Mar 4, 2016 at 1: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: what are you actually trying to do? Commented Mar 4, 2016 at 1:55
  • Have you checked out stackoverflow.com/questions/5117127/… ? Commented Mar 4, 2016 at 2:04
  • MAGIC = eval, but you really should not. Store all the possible arrays in an object, and reference them by a dynamic property name. Commented Mar 4, 2016 at 2:04

1 Answer 1

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/

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

1 Comment

Thanks. That worked!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.