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]);
}
}
这本字典是大问题就在这里。它需要实际上对内存位置进行散列,因为即使是每个对象散列码函数也不是唯一的。
有没有更好的方法来做到这一点?
这很完美。如果只有跨浏览器的支持更好。尤其是铬在这里像一个拇指疼痛伸出。 – MgSam
是的,但你可以在github上找到一个WeakMap实现。 – Halcyon