I have
var myFirstArray = [{letter: 'a'}, {letter: 'b'}, {letter: 'c'}];
I would like to make a reference to myFirstArray, so I do this:
var mySecondArray = myFirstArray;
Pushing, splicing, modifying elements in myFirstArray will be shown in mySecondArray, but if I want to reset that array to something else:
myFirstArray = [];
or
myFirstArray = someOtherData;
My reference is lost. I understand why this is, but I want mySecondArray to point at whatever myFirstArray is pointing at, at any time. What's the best way to do this?
My workarounds include:
// Just empty the array and push it:
while (myFirstArray.length) myFirstArray.pop();
for (var x in data) myFirstArray.push(x);
// Or put the array in an object:
var viewBag = {};
viewBag.myFirstArray = [...];
var mySecondArray = viewBag.myFirstArray;
I dislike both of these options :(
Edit: Consider another scenario:
function doSomethingToMyArray (theArray) {
// Say I get new data that will be formatted the way I want it to be
// Shouldn't I be allowed to do this?
var myNewData = [{ letter: 'd' }];
theArray = myNewData;
}
var myFirstArray = [{letter: 'a'}, {letter: 'b'}, {letter: 'c'}];
doSomethingToMyArray (myFirstArray);
// At this point, myFirstArray will still be a, b, c instead of d
myFirstArray.length = 0;will clear your Array for both, if that's all that you need to do. If you wish to totally replace the contents then:myFirstArray.length = 0; myFirstArray.push.appy(myFirstArray, someOtherData);. These will both affectmySecondArrayas well, provided you're made it referencemyFirstArrayas your question implies.