开发者

Pushing reference of an object to array

开发者 https://www.devze.com 2022-12-28 02:23 出处:网络
As far as i can see in a situation like this: var x = []; var y = {}; y.someProp=\'asd\'; This doesnt work:

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 "dele开发者_运维百科te y;" I want it also to be removed from the array x.


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.


That's not how delete works. It will delete the object reference you pass to it - not any other references to the same object. You're looking for something like a "weak reference" here and I'm not aware of any ways of implementing those in JavaScript.


Would this help?

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

Edit: Sorry, I was a bit brief in my first attempt at answering. What I'd start asking is: why does y need to "exist" outside of the array in the first place? Can't you just create an array of objects and use delete or array.splice() to remove the object when you need to?

Second, if y needs to exist outside of the array, what you need to do is either to create a property that refers to the array index, or a utility function that can scan through the array to find the correct object reference to remove. In other words, something like

var x=[]; var y={}; y.arrayIndex=(x.push(y)-1);

// later on, you want to get rid of y

delete x[y.arrayIndex]; delete y;


This doesnt work:

x.push(y);

Of course it does, it will work exactly as intended - pushing the value of y to the array you created.

The delete operator is specifically for deleting properties on objects, if the expression following the operator does not resolve to a property then nothing happens at all.

var y = {"someprop":true};

delete y;
alert(y.someprop); // alerts "true"

Try it in your browser window, paste the following into your address bar and hit enter:

javascript:var y = {"someprop":true}; delete y; alert(y.someprop);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号