简体   繁体   English

从 function 传递局部变量成为全局变量

[英]Passing local variables from a function out to become global variables

I've spent the last two hours trying to figure out how to do this but nothing is working.我花了过去两个小时试图弄清楚如何做到这一点,但没有任何效果。 Here is a short sample of some of my code.这是我的一些代码的简短示例。 I want to get arrtime and several other similar variables out of the function so I can use them globally.我想从 function 中获取 arrtime 和其他几个类似的变量,以便我可以全局使用它们。 Any ideas?有任何想法吗? Nothing too complicated please, I'm no expert (obviously).请不要太复杂,我不是专家(显然)。

function showTest(str) {
........

        var arrayvals = JSON.parse(xmlhttp.responseText);
        var arrtime= (arrayvals[0]);
}
var testvar=arrtime;
document.getElementById("testing").innerHTML=testvar;   

The clean way to do this is using js-object notation:干净的方法是使用 js-object 表示法:

function showTest(str) {
    //other code
    return {arr: arrayvals, tm: arrtime};
}

var func_result = showTest("blah-blah");
var testvar =func_result.tm;
var testvar2=func_result.arr;

But it's generally a bad idea to have global vars.但是拥有全局变量通常不是一个好主意。 Why do you need it?你为什么需要它?

Update sample code with global object使用global object更新示例代码

globals = {};
function q(){
    globals['a'] = 123;
    globals[123] = 'qweqwe';
}
function w(){
    alert(globals.a);
    //alert(globals.123); //will not work
    alert(globals[123]); //that's OK.
}
q();
w();

You can declare the variables outside of the function.您可以在 function 之外声明变量。

var arrtime, arrayvals;

function showTest(str) {
        arrayvals = JSON.parse(xmlhttp.responseText);
        arrtime= (arrayvals[0]);
}
var testvar=arrtime;
alert (testvar);
var testvar;
function showTest(str) {
........

        var arrayvals = JSON.parse(xmlhttp.responseText);
        var arrtime= (arrayvals[0]);
        testvar = arrtime;
}
alert (testvar);

The global is to be declared outside of the score of the function but assigned inside the scope of the function.全局将在 function 的得分之外声明,但在 function 的 scope 内分配。

You simply have to omit var which indicates a variable that is only accessible from the function scope.您只需省略var ,它表示一个只能从 function scope 访问的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM