0

I have a javascript variable called temp.

ultimately, temp will equal one of many strings, let's say for now it equals "stack".

how can I set the variable (in this case stack, which is an existing global variable) to equal the string "stack", dynamically?

So if at another point in time, temp is set to "overflow", how can i set overflow = "overflow"?

Thanks for your help!

i've seen some answers mention eval and others mention using bracket ~ this[variable], but can't seem to figure this out..

d-_-b
  • 21,536
  • 40
  • 150
  • 256

2 Answers2

1

Run this and see what happens

var x = "something";

window[x] = x;

alert(window.something);

This works because javascript objects act like hashtables

But you're best not to use the window object, otherwise you might overwrite something you actually needed.

NoPyGod
  • 4,905
  • 3
  • 44
  • 72
  • Rather, it "works" because global variables are added as properties of the global object. No other execution context (function or eval) does that. – RobG Nov 14 '12 at 04:53
1

The easiest way to achieve this is to create an object to hold these dynamic variable assignments.

// object to hold temporary variables
var tempVars = {};

// as per your example, we set temp to 'overflow'
var temp = 'overflow';

// now we can set tempVars.overflow
tempVars[temp] = temp;   

you an then access 'overflow' with either tempVars.overflow or tempVars['overflow']. Technically, you can assign global variables this way by using the window object instead of tempVars, but this is a bad idea in general.

madlee
  • 647
  • 4
  • 8