简体   繁体   中英

Updating a global variable from a function

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.

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;
}

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)
}

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