简体   繁体   中英

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. 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:

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

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.

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.

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

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