Updating a global variable from a function

2019-09-02 17:44发布

问题:

There is a global variable called numbers. Function one calculates a random number and stores it in mynumber variable.

var mynumber;

function one (){
var mynumber = Math.floor(Math.random() * 6) + 1;
}

I need to use it in a separate function as belows. But an error says undefined - that means the value from function one is not updated.

function two (){
alert(mynumber);
}

How to overcome this problem. Is there a way to update the mynumber global variable.

回答1:

If you declare a variable with var it creates it inside your current scope. If you don't, it'll declare it in the global scope.

var mynumber;

function one (){
    mynumber = Math.floor(Math.random() * 6) + 1; // affects the global scope
}

You can also specify that you want the global scope even if you define a local variable too:

function one (){
    var mynumber = 1; // local
    window.mynumber = Math.floor(Math.random() * 6) + 1; // affects the global scope
}

Knowing that the global scope is window you can get pretty tricksy with modifying global variables:

function one (){
    var mynumber = Math.floor(Math.random() * 6) + 1; // local
    window['mynumber'+mynumber] = mynumber; // sets window.mynumber5 = 5 (or whatever the random ends up as)
}


回答2:

What you have:

var mynumber = Math.floor(Math.random() * 6) + 1;

Declares a new local variable and then sets a value. Drop the var and you will update the original.

function one (){
   mynumber = Math.floor(Math.random() * 6) + 1;
}