Reputation: 60
I'm using javascript. I want to have a function that can change the value of a given global variable. My code has to have the following structure:
function change(variable_name, new_value){
//Code to make it work!
}
and I want the function to work like this:
var x = 0;
change(x,2);
and at this point the variable x should be equal to 2.
Thanks and sorry for my english!
Upvotes: 0
Views: 758
Reputation: 9174
You should pass the variable name as a string
function change(variable_name, new_value){
window[variable_name] = new_value
}
var x = 0;
change('x',2); // pass the variable name as a string, instead of the variable
Upvotes: 4