iJade
iJade

Reputation: 23811

Can anyone explain the following Javascript code behaviour?

Here is my Javascript code:

var subRow = [];
var rowarr = [];
subRow.push({ v: "Jay" });
subRow.push({ v: "Ram" });
rowarr.push({ c: subRow });
subRow.length = 0;
subRow.push({ v: "Jay1" });
subRow.push({ v: "Ram1" });
rowarr.push({ c: subRow });
console.log(JSON.stringify(rowarr));

The output is:

    [{
    "c": [{
        "v": "Jay1"
    }, {
        "v": "Ram1"
    }]
}, {
    "c": [{
        "v": "Jay1"
    }, {
        "v": "Ram1"
    }]
}]

The expected output is:

    [{
    "c": [{
        "v": "Jay"
    }, {
        "v": "Ram"
    }]
}, {
    "c": [{
        "v": "Jay1"
    }, {
        "v": "Ram1"
    }]
}]

Can anyone explain why it so?

Upvotes: 0

Views: 65

Answers (2)

Quentin
Quentin

Reputation: 944075

Arrays are handled by reference.

subRow.length = 0; erases the contents of the array.

rowarr then contains two pointers to the same array (which only has the content in it that you put there after emptying it)

Change subRow.length = 0; to subRow = [] to work on a new array instead of modifying the existing one.

Upvotes: 4

Patashu
Patashu

Reputation: 21793

subRow points to an object. When you push it onto rowArr you create a reference to that object. You push it twice, that's two references to one object. When you edit subRow both references to the object see the changes, so you've trampled all over the old contents of the object - they are not stored anywhere else, so they are completely lost. You need to create a brand new object instead of editing the old object.

Upvotes: 2

Related Questions