从函数更新全局变量 [英] Updating a global variable from a function

查看:141
本文介绍了从函数更新全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个叫做数字的全局变量。
函数计算一个随机数并将其存储在mynumber变量中。

  var mynumber; 

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

我需要在一个单独的函数中使用它,如下所示。但一个错误表示未定义 - 这意味着函数1的值不会更新。

 函数two(){
告警(mynumber的);
}

如何解决这个问题。有没有办法更新mynumber全局变量。

解决方案

如果用 var 它会在当前范围内创建它。如果你不这样做,它会在全局范围内声明它。

  var mynumber; 

函数one(){
mynumber = Math.floor(Math.random()* 6)+ 1; //影响全球范围
}

您也可以指定您希望全局范围即使您也定义了一个局部变量:

  function one(){
var mynumber = 1; // local
window.mynumber = Math.floor(Math.random()* 6)+ 1; //影响全球范围
}

知道全局范围是 window 你可以通过修改全局变量来获得相当高的技巧:

  function one(){
var mynumber = Math.floor(Math.random()* 6)+ 1; // local
window ['mynumber'+ mynumber] = mynumber; //设置window.mynumber5 = 5(或者任何随机结果为)
}


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.

解决方案

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

这篇关于从函数更新全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆