Js remove object reference from two arrays

When the same object reference exists in two arrays, the objects are equivalent and one update affects the other.

However, deleting an object from one array does not delete it in another.

Why not?

var a1 = [
  {i: 0, s: 'zero'}, 
  {i: 1, s: 'one'}
];

var a2 = [
  a1[0],
  a1[1]
];

// items point to same reference
print(a1[0] === a2[0]); // true (equivalent)

// updating one affects both
a1[0].s += ' updated';
print(a1[0] === a2[0]); // true (still equivalent)
print(a1[0]); // {"i":0,"s":"zero updated"}
print(a2[0]); // {"i":0,"s":"zero updated"}

// however, deleting one does not affect the other
delete a1[0];
print(a1[0]); // undefined
print(a2[0]); // {"i": 0, "s": "zero"}

      

Interestingly, removing a property from one affects the other.

delete a1[1].s;
print(a1[1]); // {"i":1}
print(a2[1]); // {"i":1}

      

https://jsfiddle.net/kevincollins/4j6hj2v7/3/

+3


source to share


2 answers


To answer why the latter print(a2[0]);

still shows a value, let's start analyzing the code.

Yours a1

is an array, and when you initialize it with objects, it will create objects and keep their reference.

var a1 = [
  {i: 0, s: 'zero'}, // ref 1001
  {i: 1, s: 'one'}   // ref 1002
];

      

This part is clear from your comments, but what happens when you do delete a1[0]

?



Will the object be deleted? Answer no. It will remove the property stored at 0

th index in a1

and set it to undefined

. But if you remove the property of the object contained in this link, it will show up in both: sample

What happens to the object? The value is saved and will be garbage collected if no one is referencing it. In your case, since a2[0]

everything is still accessing it, it will retain the value.

You can check the sample for reference.

+1


source


As @Halcyon said, you are removing the link, not the object itself. To demonstrate, take a look at the following example:

var a = 2
var b = [a, 2, 3, 4]

      



If you come to delete b[0]

, you will only remove the link, and thus a===2

. However, if you must remove the link in a

, through delete a

, then the value in b

will be changed to undefined

because the link that previously existed in that location no longer does

0


source







All Articles