Updating a global variable from a function

空扰寡人 提交于 2020-01-06 17:42:32

问题


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


来源:https://stackoverflow.com/questions/25917425/updating-a-global-variable-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!