我有类似的东西
var myArray = [];
myArray.push(someObject);
但是如果我删除或拼接那个数组条目我只是推它也删除someObject(someObject通过推送传递,而不是克隆,我不能让它成为克隆)。我有什么方法可以:
答案 0 :(得分:1)
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