javascript 将函数中的局部变量传递出去成为全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7093084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:57:03  来源:igfitidea点击:

Passing local variables from a function out to become global variables

javascriptvariablesgloballocal

提问by Peter

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. Any ideas? Nothing too complicated please, I'm no expert (obviously).

我花了最后两个小时试图弄清楚如何做到这一点,但没有任何效果。这是我的一些代码的简短示例。我想从函数中获取 arrtime 和其他几个类似的变量,以便我可以全局使用它们。有任何想法吗?请不要太复杂,我不是专家(显然)。

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

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

回答by J0HN

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?

但是拥有全局变量通常是一个坏主意。你为什么需要它?

Updatesample code with globalobject

使用global对象更新示例代码

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();

回答by Thilo

You can declare the variables outside of the function.

您可以在函数之外声明变量。

var arrtime, arrayvals;

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

回答by Joseph Marikle

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.

global 将在函数的分数之外声明,但在函数的范围内分配。

回答by Van Coding

You simply have to omit varwhich indicates a variable that is only accessible from the function scope.

您只需省略varwhich 表示只能从函数范围访问的变量。