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开发者_如何学JAVA);
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.
精彩评论