If the variable is in the global scope, you can access it as a property of the global object
var a = "hello world"; var varName = "a"; console.log( window[varName] ); // outputs hello world console.log( this[varName] ); // also works (this === window) in this case
However, if it is a local variable, the only way is to use eval ( disclaimer )
function () { var a = "hello world"; var varName = "a"; console.log( this[varName] );
If you cannot put your dynamic variables in an object and access it as a property
function () { var scope = { a: "hello world"; }; var varName = "a"; console.log( scope[varName] );
Juan Mendes Jun 08 '12 at 17:27 2012-06-08 17:27
source share