Reputation: 36759
var foo = "bar"
var bar = "realvalue";
Is it possible to print the value of bar
using foo
?
Upvotes: 31
Views: 1260
Reputation: 173572
Don't do this kind of constructs with non-global variables, just scope whatever variables you would otherwise have floating around.
var myscope = {
bar: 'realvalue'
},
foo = 'bar';
alert(myscope[foo]);
Btw, the above doesn't rely on the default behaviour of browsers to also register global variables in the window
object, making it work for things like Node.js too.
Upvotes: 10
Reputation: 24334
Yeah you can do something like this with eval
var foo = "bar";
var bar = "realvalue";
alert(eval(foo));
EDIT: Seems a lot of people are against using the eval() function. My advice before using it is read this question: Why is using the JavaScript eval function a bad idea?
Then once you understand the risks you can decide for yourself if you wish to use it.
Upvotes: 17
Reputation: 12683
Approach 1: global variable
var foo = "bar";
var bar = "realvalue";
alert(window[foo]);
OR
Approach 2: namespace
Divide your js to namespaces
var namespace = {
foo : "bar",
bar : "realvalue"
};
alert(namespace[namespace.foo]);
Upvotes: 44
Reputation: 97
var foo = "bar";
var bar = "realvalue";
foo=bar;
console.log(foo);
alert(foo);
Upvotes: 2
Reputation: 73906
Global variables are defined on the window
object, so you can use:
var bar = "realvalue";
alert(window["bar"]);
Upvotes: 2
Reputation: 14346
Yes, via eval
. But unfortunately, not without eval
, which is a bad idea to use.
Upvotes: 0