2012-03-08 52 views
0

對象刪除陣列項目我有這樣的事情而不刪除它指向

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

但當時如果我刪除或拼接數組進入我只是把它還會刪除someObject(someObject是通過引用傳遞通過推動,而不是一個克隆,我不能讓它成爲一個克隆)。有沒有什麼辦法可以:

  1. 剛剛從myArray的移除指向someObject並沒有實際刪除someObject
  2. 有它刪除陣列中的對象的實際關鍵,但並不是所有的其他鍵移位陣列?
+0

你是什麼意思與 「刪除someObject」?當一個對象沒有更多的引用時,它只會在JavaScript中被GC化。所以如果仍然指向它,它不會丟失。 – ThiefMaster 2012-03-08 23:49:21

+0

你是什麼意思「刪除someObject」?引用該對象的任何其他變量都應該繼續這樣做。 – Chuck 2012-03-08 23:49:32

+0

爲什麼你認爲'.splice'刪除'someObject'? '.splice()'從數組中刪除元素,但是這些元素是對象,它不會刪除實際的對象 - 但是您需要對這些對象進行一些其他引用才能繼續使用它們。因此,如果'someObject'變量仍然引用該對象,那麼在從數組中移除引用後仍然可以使用該對象。 '.splice()'實際上返回一個已刪除項目的數組,所以... – nnnnnn 2012-03-08 23:50:25

回答

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 
+0

謝謝,這對我來說非常合適! – Macmee 2012-03-09 02:06:44

相關問題