简体   繁体   English

对象图的JavaScript深层复制

[英]JavaScript deep copy of an object graph

I need a function which makes a deep copy of an object in JavaScript. 我需要一个能够在JavaScript中复制对象的深层功能的函数。 Each object is part of a larger graph (thus the need for a deep copy function). 每个对象都是较大图的一部分(因此需要深度复制功能)。 For example, 例如,

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

The graph has no loops. 该图没有循环。

My thought was to do a depth-first-search through the graph and use a dictionary that stores a hash of each Node with its copy. 我的想法是对图形进行深度优先搜索,并使用一个字典来存储每个Node的哈希值及其副本。 As each node is visited, the copy parent is looked up from the dictionary and the node is added to its parents children collection. 在访问每个节点时,将从字典中查找复制父对象,并将该节点添加到其父子对象集合中。 My problem is that for this method to work, I'd need to be able to has on the memory location of each Node. 我的问题是,要使此方法起作用,我需要能够掌握每个Node的内存位置。

This was my general idea: 这是我的一般想法:

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]);
    }
}

The dictionary is the big problem here. 字典在这里是个大问题。 It would need to actually hash on the memory location, because even a hashcode function could not be unique per object. 它实际上需要在内存位置上进行哈希处理,因为即使哈希码函数也不能对每个对象唯一。

Is there a better way to do this? 有一个更好的方法吗?

Rather than using hashcodes you can use a WeakMap . 除了使用哈希码,还可以使用WeakMap They essentially do the same thing: give you a uniqueness detector. 他们本质上是在做同样的事情:为您提供唯一性检测器。 But without the cost of the hashing algorithm, it's collision free and doesn't use much memory. 但是没有散列算法的成本,它没有冲突并且不占用太多内存。

Support for WeakMaps 支持WeakMaps

If you search you can find custom implementations of WeakMaps incase you're using a browser that doesn't support WeakMaps yet. 如果您搜索,则可以找到WeakMaps的自定义实现,以防万一您使用的浏览器尚不支持WeakMaps。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM