I have multiple global arrays that a single method performs operations on. The method will only need to operate on one array at a time. I would like to accomplish this by passing a parameter to the method and then let the method decide which array it needs to modify based on that parameter. For example,
var globalarray1;
var globalarray2;
Operate(globalarray1);
function Operate(globalarray){
globalarray.push("test");
}
Of course, the code above only changes the value of the array local to the scope of the method. I know I can do something like this:
var globalarray1;
var globalarray2;
Operate(1);
function Operate(flag){
if (flag == 1){
globalarray1.push("test1");
}
else if (flag == 2){
globalarray2.push("test2")
}
}
However, it just doesn’t feel right. How can I change the value of the globals using parameters in a single method without using a bunch of conditional statements?
Your first approach is correct. This statement, however, is not:
Array objects
are passed by referencecalled by sharing (i.e. the reference is passed by value, not the value itself). When you pass the array to the method, it can (and in your case does) actually modified the global variable. This would not be the case if you passed in an immutable or primitive value such as a number or a string. In those cases, the value is in fact local to the scope of the method.The fact that your variables are global have nothing to do with it. Take this code, for example:
Above, localArray is not a global variable, but it can still be affected by Operate() if you pass the array in directly.