[英]JavaScript deep copy of an object graph
我需要一個能夠在JavaScript中復制對象的深層功能的函數。 每個對象都是較大圖的一部分(因此需要深度復制功能)。 例如,
//Node "class" with references to its parent and children
var MyNode = (function () {
function MyNode() {
this.children = undefined;
this.parent = undefined;
}
return MyNode;
})();
該圖沒有循環。
我的想法是對圖形進行深度優先搜索,並使用一個字典來存儲每個Node的哈希值及其副本。 在訪問每個節點時,將從字典中查找復制父對象,並將該節點添加到其父子對象集合中。 我的問題是,要使此方法起作用,我需要能夠掌握每個Node的內存位置。
這是我的一般想法:
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]);
}
}
字典在這里是個大問題。 它實際上需要在內存位置上進行哈希處理,因為即使哈希碼函數也不能對每個對象唯一。
有一個更好的方法嗎?
除了使用哈希碼,還可以使用WeakMap
。 他們本質上是在做同樣的事情:為您提供唯一性檢測器。 但是沒有散列算法的成本,它沒有沖突並且不占用太多內存。
如果您搜索,則可以找到WeakMaps的自定義實現,以防萬一您使用的瀏覽器尚不支持WeakMaps。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.