Greg Pete
Greg Pete

Reputation: 69

Keeping Javascript reference after setting the reference to something else

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

Upvotes: 0

Views: 63

Answers (2)

user3727707
user3727707

Reputation:

What is happen is that when you set the parent variable to a new value, the watchers are lost and the changes aren't applied to the child.

You need to do this extremely obnoxious convention of putting the file in a data map.

So, instead of:

var myFirstArray

Use:

$scope.data = {}; $scope.data.myFirstArray = blah;

I highly recommend giving the data object a smarter name is possible.

Another problem you could be experiencing is the "dot problem", which is explained in this blog post.

Upvotes: 0

TRGWII
TRGWII

Reputation: 648

Why not just set mySecondArray whenever you set myFirstArray?

A good tip for setting variables quickly is this syntax:

var mySecondArray, myFirstArray;

mySecondArray = myFirstArray = ["somevalue"];

In JavaScript, when you set myFirstArray to something like [], and then mySecondArray to myFirstArray, it won't reference the first variable, but both variables will reference the same actual array.

Upvotes: 1

Related Questions