I have the following variable:
var MyVar = "8";
I have 2 strings for example:
var foo = "My";
var bar = "Var";
Now I want to alert MyVar value, meaning to alert "8" and not "MyVar"
alert(foo + bar) // returns "MyVar"
I have the following variable:
var MyVar = "8";
I have 2 strings for example:
var foo = "My";
var bar = "Var";
Now I want to alert MyVar value, meaning to alert "8" and not "MyVar"
alert(foo + bar) // returns "MyVar"
This is a rare case where eval
will be needed:
Code
var MyVar = "8",
foo = "My",
bar = "Var";
alert(eval(foo + bar))
Assuming it's a global variable:
alert(window[foo + bar])
But you're probably better off using objects and properties for that. Object properties can also be accessed with bracket notation:
var obj = {
MyProp : 8
};
var foo = "My";
var bar = "Prop";
alert(obj[foo + bar]);
Without changing the context to much of what you are doing you can use the eval
function. However, you have to be very careful with it.
var MyVar = 8;
var foo = "My";
var bar = "Var";
alert(eval(foo + bar));
Depending on what your doing though there are a lot of ways to do this. If you assign MyVar
to be part of some context such as this
, or window
you can simply lookup the value with the key as the variable name.
Window Context
(function () {
window.MyVar = 8;
var foo = "My";
var bar = "Var";
alert(window[foo+bar]);
})();
Function Context
new (function () {
this.MyVar = 8;
var foo = "My";
var bar = "Var";
alert(this[foo+bar]);
})();
Object Context
(function () {
var obj = {}
obj.MyVar = 8;
var foo = "My";
var bar = "Var";
alert(obj[foo+bar]);
})();