Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing reference of an object to array

As far as i can see in a situation like this:

var x = [];
var y = {};

y.someProp='asd';

This doesnt work:

x.push(y);

What I want to do is add a reference of y to x so that later if I will "delete y;" I want it also to be removed from the array x.

like image 637
intacto Avatar asked Sep 02 '25 06:09

intacto


1 Answers

You are mixing up variables, references and objects.

Doing delete y; removes the variable y. As the variable no longer exists, it will naturally no longer have a value. Thus the reference that the variable contained is gone.

Removing the variable will however not in itself remove the object that it was referencing. The array still contains a reference to the object, and neither of those depend on the existance of the variable.

There is actually no way of removing the object directly. You remove objects by destroying all references to it, not the other way around. You want the object to remove it's references, which is simply not how it works.

like image 172
Guffa Avatar answered Sep 04 '25 21:09

Guffa