Alexander Zeitler
Alexander Zeitler

Reputation: 13109

Copies of nested arrays and references in javascript

The following javascript code [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);?

results in:

before removing
master1 parents: 2
master2 parents: 2
master1 parent 1 childrens: 2
master2 parent 2 childrens: 2
after removing
master1 parents: 1
master2 parents: 2
master1 parent 1 childrens: 1
master2 parent 2 childrens: 1

I would expect (and need) this:

before removing
master1 parents: 2
master2 parents: 2
master1 parent 1 childrens: 2
master2 parent 2 childrens: 2
after removing
master1 parents: 1
master2 parents: 2
master1 parent 1 childrens: 1
master2 parent 2 childrens: 2 <-- difference

What am I doing wrong? It looks like the childs are referring to the same array also I did slice the initial children array (which did work with the parent array as expected).

Upvotes: 1

Views: 150

Answers (1)

Golo Roden
Golo Roden

Reputation: 150842

Having a look at http://de.selfhtml.org/javascript/objekte/array.htm#slice could deliver a potential answer (translation done by me):

"Please note: If there is an object contained within the array, the newly created array contains a reference to that object. That means: If the object is changed, so does the array that was created using slice(). If numbers and strings are contained, they are copied."

Should explain why both change, shouldn't it?

Upvotes: 3

Related Questions