views:

105

answers:

6

Is there a way to refer to a Javascript variable with a string that contains its name?

example:

var myText = 'hello world!';
var someString = 'myText';

//how to output myText value using someString?
+1  A: 

You can do this with eval:

var myText = 'hello world!';
var someString = 'myText';

eval('var theTextInMyText = ' + someString + ';');

alert(theTextInMyText);

The desire to do this at all usually is a "code smell". Perhaps there is a more elegant way...

Asaph
+8  A: 

You can use an eval to do it, though I try to avoid that sort of thing at all costs.

alert(eval(someString));

A better way, if you find yourself needing to do this, is to use a hash table.

var stuff = { myText: 'hello world!' };
var someString = 'myText';
alert( stuff[someString] );
friedo
+1  A: 
eval("alert(" + someString + ");");

would work.

Justin Niessner
+1  A: 

eval will do that:

var myText = 'hello world!!';
var someString = eval('myText');

document.getElementById('hello').innerHTML = someString;

As demonstrated here.

Michael Haren
+6  A: 

If that variable is on the global scope, you can use the bracket notation on the global object:

var myText = 'hello world!';
var someString = 'myText';

alert(window[someString]);
CMS
+1  A: 

Assuming this is at the top level, window[someString] === "hello world!".

nlogax