I have a global object, and I'm trying to pass its reference into a function, and then change the object that reference points to in the function called. Here is an example of the problem with a simple 3 element array:
var myObject = [1, 2, 3]; //this is global
changeObject(myObject);
function changeObject(obj) {
$('#beforeLocal').html( obj.toString() );
$('#beforeGlobal').html( myObject.toString() );
obj = [4, 5, 6];
$('#afterLocal').html( obj.toString() );
$('#afterGlobal').html( myObject.toString() );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Local array before changing: <span id="beforeLocal"></span></p>
<p>Global array before changing: <span id="beforeGlobal"></span></p>
<p>Changing local array</p>
<p>Local array after changing: <span id="afterLocal"></span></p>
<p>Global array after changing: <span id="afterGlobal"></span></p>
However, when changing the local object, it only changes the local reference, and not the global one. I know that in this example,
obj[0] = 4;
obj[1] = 5;
obj[2] = 6;
would work.
I want to achieve this without cycling through all the values of the array, and also I want it to work for arrays of different sizes and/or objects in general.
I need to do this in this way because I need a general function, so I can't reference the global array directly inside the function (because it needs to work for multiple arrays) and I also cannot use the return value because this is something I need to do asynchronously (this is a simplified problem).