简体   繁体   中英

How can I change global variables in javascript?

My html page displays a button that calls a function when it is clicked. I checked to make sure that the button works properly by displaying a message when clicked and it worked. I created this function to change the global varible but when I click another button on my html page to show the value of the varibles the varibles have not changed to the value I set them using my function. Could someone find the problem in my code below?

    var a = 5;
    var b = 16;
    var c = 27;

    function reset(){
    a = 0;
    b = 0;
    c = 0;
    }

My html code to call the function:

   <!DOCTYPE HTML>

   <html>
   <center>
   <script type="text/javascript" src="game.js" > </script>
   <form>
   <input type="button" value="Reset Variables" style="width:250px;height:50px" onclick="reset()" >
   </form>
   </html>

Javascript code to show the variables:

    function display(){

    document.write("A is equal to " + a + "<br/>");
    document.write("B is equal to " + b + "<br/>");
    document.write("C is equal to " + c );

}

Html to display the variables

   <!DOCTYPE HTML>

   <html>
   <center>
   <script type="text/javascript" src="game.js" > </script>
   <form>
   <input type="button" value="Show Variables" style="width:250px;height:50px" onclick="display()" >
   </form>
   </html>

That can`t work, because you are asserting that variables in function scope. But your variables are currently stored in global scope (window), so this code will work:

var a = 5;
function reset() {
    console.log(window.a); // 5
    window.a = 10;
}
reset();
console.log(a); // 10

change the function name to reset_vars or anything else. reset() is in-built DOM function used for resetting forms.

http://www.w3schools.com/jsref/met_form_reset.asp

There won't be any conflict when a global variable is used inside a function unless a local variable is defined. in such case, use window.variable_name to access global 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