我有这样的东西
var myArray = [];
myArray.push(someObject);
但是如果我删除或拼接我刚刚推送的那个数组条目,它也会删除 someObject(someObject 是通过推送通过引用传递的,而不是克隆,我不能让它成为克隆)。有什么办法可以:
- 只需从 myArray 中删除指向 someObject 的指针,而不实际删除 someObject
- 它是否删除了数组中对象的实际键,但不移动数组中的所有其他键?
我有这样的东西
var myArray = [];
myArray.push(someObject);
但是如果我删除或拼接我刚刚推送的那个数组条目,它也会删除 someObject(someObject 是通过推送通过引用传递的,而不是克隆,我不能让它成为克隆)。有什么办法可以:
只要 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