简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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