Access value of JavaScript variable by name?

Hello it is possible to access the value of a JavaScript variable by name? Example:

var MyVariable = "Value of variable";


function readValue(name) {
     ....
}


alert(readValue("MyVariable"));

Is this possible, so that the output is "Value of variable"? If yes, how do I write this function?

Thanks


Solution 1:

Global variables are defined on the window object, so you can use:

var MyVariable = "Value of variable";
alert(window["MyVariable"]);

Solution 2:

Yes, you can do it like this:

var MyVariable = "Value of variable";
alert(window["MyVariable"]);

Solution 3:

var MyVariable = "Value of variable";    
alert(readValue("MyVariable"));    

// function readEValue(name) { readevalue -> readvalue // always do copy-paste to avoid errors  
function readValue(name) {   
 return window[name]   
}   

That's all about ;o)