删除数组中的项目而不删除它指向的对象

时间:2012-03-08 23:42:29

标签: javascript arrays pointers splice

我有类似的东西

var myArray = [];
myArray.push(someObject);

但是如果我删除或拼接那个数组条目我只是推它也删除someObject(someObject通过推送传递,而不是克隆,我不能让它成为克隆)。我有什么方法可以:

  1. 只需从myArray中删除指向someObject的指针,而不实际删除someObject
  2. 是否删除了数组中对象的实际键,但没有移动数组中的所有其他键?

1 个答案:

答案 0 :(得分:1)

只要javascript中的某些其他变量或对象引用someObject,

someObject就不会被删除。如果没有其他人有引用它,那么它将被垃圾收集(由javascript解释器清理),因为当没有人引用它时,无论如何它都不能被你的代码使用。

以下是相关示例:

var x = {};
x.foo = 3;

var y = [];
y.push(x);
y.length = 0;   // removes all items from y

console.log(x); // x still exists because there's a reference to it in the x variable

x = 0;          // replace the one reference to x
                // the former object x will now be deleted because 
                // nobody has a reference to it any more

或采用不同的方式:

var x = {};
x.foo = 3;

var y = [];
y.push(x);      // store reference to x in the y array
x = 0;          // replaces the reference in x with a simple number

console.log(y[0]); // The object that was in x still exists because 
                   // there's a reference to it in the y array

y.length = 0;      // clear out the y array
                   // the former object x will now be deleted because 
                   // nobody has a reference to it any more