简体   繁体   中英

How do I change the value of any global variable inside of a function?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM