[英]Remove item in array without deleting the object it points to
我有这样的东西
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.