只要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
你是什麼意思與 「刪除someObject」?當一個對象沒有更多的引用時,它只會在JavaScript中被GC化。所以如果仍然指向它,它不會丟失。 – ThiefMaster 2012-03-08 23:49:21
你是什麼意思「刪除someObject」?引用該對象的任何其他變量都應該繼續這樣做。 – Chuck 2012-03-08 23:49:32
爲什麼你認爲'.splice'刪除'someObject'? '.splice()'從數組中刪除元素,但是這些元素是對象,它不會刪除實際的對象 - 但是您需要對這些對象進行一些其他引用才能繼續使用它們。因此,如果'someObject'變量仍然引用該對象,那麼在從數組中移除引用後仍然可以使用該對象。 '.splice()'實際上返回一個已刪除項目的數組,所以... – nnnnnn 2012-03-08 23:50:25