View Full Version : Set global variable
momal_1
11-24-2004, 12:20 PM
Hi,
I have a funtion which takes in a global variable.
My problem is how do i set this global variable from within the ***ntion.
Example:
var jvar1 = 0;
function variabletest(jval) {
var j = jval
j += 1;
jval = j;
}
And i call the by using
variabletest(jvar1)
First time round this should go to 1, but it stays at zero as it cannot update this outside variable. Im hopin to set jvar1 to the value of jvar/j
The answer maybe really obvious!
Thanks
Jon Hanlon
11-24-2004, 07:43 PM
Computer Science 101
Javascript usually passes parameters to functions via value. This means that the function only gets told the value of each parameter. Any changes made to the parameter are actually made to a local copy, so aren't permanent.
What you want to do involves passing by reference, where the function is supplied with the memory address of the parameter. Javascript will pass by reference if the parameter is an Object (including Arrays).
http://www.webreference.com/js/tips/010210.html
http://academ.hvcc.edu/~kantopet/javascript/index.php?page=using+js+arrays&parent=js+arrays
function incr(x) { // x is an object
x.val = x.val + 1;
}
yy = new Object();
yy.val = 127;
incr(yy);
alert(yy.val); // shows 128
The easiest solution is to pass a string representing the variable:
function incr(x) { // x is a string
eval(x + " += 1")
}
forty = 40;
incr("forty");
alert(forty); // shows 41
Of course you do know that you can access global variables from inside functions:
var errorCount = 0; // global variable
function addError() {
// blah blah blah
errorCount += 1;
}
Just don't put var in front of it.
momal_1
11-25-2004, 10:56 AM
I have tried all your suggestions but still cannot get it to work.
I have 3 variables which could be passed in depending on the user:
var jval1 = 0;
var jval2 = 0;
var jval3 = 0;
then i call it using the above function, it does not change the global vaiable at all. If i call the metod again, the variable is still at 0 which i cannot understand.
Is there a simpler way in which i can reference this variable
Thanks
vBulletin® v3.6.7, Copyright ©2000-2009, Jelsoft Enterprises Ltd.