javascript中嵌套数组和引用的副本

时间:2012-04-14 13:01:22

标签: javascript

以下javascript代码[jsfiddle]:

Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

var masterlist = [{
    name: "Master1"},
{
    name: "Master2"}];
var parentlist = [{
    name: "Parent1"},
{
    name: "Parent2"}];
var childlist = [{
    name: "Child1"},
{
    name: "Child2"}];

for (var i = 0; i < masterlist.length; i++) {
    var master = masterlist[i];
    master.parents = parentlist.slice();
    for (var j = 0; j < master.parents.length; j++) {
        var parent = master.parents[j];
        parent.children = childlist.slice();
    }
}

console.log("before removing")
console.log("master1 parents: " + masterlist[0].parents.length);
console.log("master2 parents: " + masterlist[1].parents.length);
console.log("master1 parent 1 childrens: " + masterlist[0].parents[0].children.length);
console.log("master2 parent 2 childrens: " + masterlist[1].parents[1].children.length);

masterlist[0].parents.remove(0);
masterlist[0].parents[0].children.remove(0);

console.log("after removing")
console.log("master1 parents: " + masterlist[0].parents.length);
console.log("master2 parents: " + masterlist[1].parents.length);
console.log("master1 parent 1 childrens: " + masterlist[0].parents[0].children.length);
console.log("master2 parent 2 childrens: " + masterlist[1].parents[1].children.length);?

结果:

在删除之前 master1父母:2
master2父母:2
master1 parent 1 childrenrens:2
master2 parent 2 childrenrens:2
删除后 master1父母:1
master2父母:2
master1 parent 1 childrenrens:1
master2 parent 2 childrenrens:1

我希望(并且需要)这个:

在删除之前 master1父母:2
master2父母:2
master1 parent 1 childrenrens:2
master2 parent 2 childrenrens:2
删除后 master1父母:1
master2父母:2
master1 parent 1 childrenrens:1
master2 parent 2 childrenrens:2&lt; - difference

我做错了什么? 看起来孩子们指的是同一个数组,我也切片初始的子数组(它确实与父数组一起工作)。

1 个答案:

答案 0 :(得分:3)

查看http://de.selfhtml.org/javascript/objekte/array.htm#slice可以提供一个可能的答案(由我完成的翻译):

“请注意:如果数组中包含对象,则新创建的数组包含对该对象的引用。这意味着:如果更改了对象,则使用slice()创建的数组也是如此。包含数字和字符串,它们被复制。“

应该解释为什么两者都改变​​了,不应该吗?