复制对象不会对我的代码产生影响

时间:2015-03-20 07:12:01

标签: javascript jquery d3.js clone

我想要复制一个对象source,而copy更改,source不应该更改。源代码如下:

layoutTreemap: function(source) {

    var copy = jQuery.extend(true,{},source);

    var select_polygon = this.get_selected_polygon();

    var vt = d3.layout.voronoitreemap()

    var layoutNodes = vt(copy);

    return layoutNodes;
}

d3.layout.voronoitreemap = function() {
    var hierarchy = d3.layout.hierarchy().sort(null),
    root_polygon = [[0,0],[500,0],[500,500],[0,500]], 
    iterations = 100,
    somenewvariable = 0;

    function voronoitreemap(d, depth) {
    var nodes = hierarchy(d),
    root = nodes[0];

    root.polygon = root_polygon;
    root.site = null;

    if (depth != null){
        max_depth = depth;
    }
    else{
        max_depth = "Infinity";
    }

    computeDiagramRecursively(root, 0);

    return nodes;
    }

    function computeDiagramRecursively(node, level) {
    var children = node.children;
    if(node.parent) node.parent = null;


    if (children && children.length && level < max_depth) {
        node.sites = VoronoiTreemap.init(node.polygon, node);  // can't say dataset, how about node?
        VoronoiTreemap.normalizeSites(node.sites);
        VoronoiTreemap.sites = node.sites;
        VoronoiTreemap.setClipPolygon(node.polygon);
        VoronoiTreemap.useNegativeWeights = false;
        VoronoiTreemap.cancelOnAreaErrorThreshold =  true;
        var polygons = VoronoiTreemap.doIterate(iterations);

        // set children polygons and sites
        for (var i = 0; i < children.length; i++) {
        children[i].polygon = polygons[i];
        children[i].site = VoronoiTreemap.sites[i];

        computeDiagramRecursively(children[i], (level + 1));

        }

    }
    }
    ....

    return d3_layout_hierarchyRebind(voronoitreemap, hierarchy); 
}

但执行vt(copy)后,source已更改。

1 个答案:

答案 0 :(得分:0)

这会产生问题

root.polygon = root_polygon;
children[i].polygon = polygons[i];

您正在复制您认为的阵列。但实际上你正在复制对数组的引用。现在你有两个指向同一个对象的指针(想象两个人在晚餐时使用相同的叉子)

您需要将其更改为

root.polygon = root_polygon.slice();
children[i].polygon = polygons[i].slice();

这样就可以复制数组而不是引用数组。现在每位晚餐客人都有自己的叉子。