2013-08-28 63 views
1

我需要一個在JavaScript中創建對象的深層副本的函數。每個對象都是較大圖形的一部分(因此需要深度複製功能)。例如,對象圖的JavaScript深層副本

//Node "class" with references to its parent and children 
var MyNode = (function() { 
    function MyNode() { 
     this.children = undefined; 
     this.parent = undefined; 
    } 
    return MyNode; 
})(); 

該圖沒有循環。

我的想法是對圖進行深度優先搜索,並使用一個存儲每個節點散列的副本的字典。在訪問每個節點時,將從字典中查找副本父節點,並將該節點添加到其父母子集合中。我的問題是,這種方法的工作,我需要能夠在每個節點的內存位置。

這是我的總體思路:

function(rootNode) { 
    var magicDictionary = {}; 
    var stack = {rootNode}; 

    while(stack.length > 0) { 
     var current = stack.pop(); 

     //Performs a shallow copy, not including the parent or children references 
     var newNode = new MyNode(current); 

     //Get our new node's parent based on our old node's parent 
     newNode.parent = magicDictionary[current.parent]; 

     //Add this new node as a child 
     newNode.parent.children.push(newNode); 

     //Continue the DPS 
     for(var i = 0; i < current.children.length; i++) 
      stack.push(current.children[i]); 
    } 
} 

這本字典是大問題就在這裏。它需要實際上對內存位置進行散列,因爲即使是每個對象散列碼函數也不是唯一的。

有沒有更好的方法來做到這一點?

回答

1

您可以使用WeakMap而不是使用哈希碼。他們基本上做同樣的事情:給你一個唯一性檢測器。但是,如果沒有散列算法的成本,那麼它就沒有衝突,並且不會佔用太多內存。

Support for WeakMaps

如果你搜索,你可以找到WeakMaps的定製實現櫃面您使用的是不支持WeakMaps又一個瀏覽器。

+0

這很完美。如果只有跨瀏覽器的支持更好。尤其是鉻在這裏像一個拇指疼痛伸出。 – MgSam

+0

是的,但你可以在github上找到一個WeakMap實現。 – Halcyon