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

前端 未结 5 763
野趣味
野趣味 2020-11-27 10:36

I am using JavaScript and I create a global variable. I define it outside of a function and I want to change the global variable value from inside a function and use it from

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 11:01

    var a = 10;
    
    myFunction(a);
    
    function myFunction(a){
       window['a'] = 20; // or window.a
    }
    
    alert("Value of 'a' outside the function " + a); //outputs 20
    

    With window['variableName'] or window.variableName you can modify the value of a global variable inside a function.

提交回复
热议问题