Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;   
like image 456
Peter Avatar asked Dec 30 '25 11:12

Peter


1 Answers

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();
like image 179
J0HN Avatar answered Jan 02 '26 00:01

J0HN