Javascript数组副本损坏

问题描述 投票:0回答:1

我在React State中有一个对象数组:this.state.expandableRowSwitches是一个对象数组:

{display:false,selected:false,ghosted:false}

当我尝试制作数组的副本来操作它(深或浅)时,如果我使用操作数组特定索引的行跟随复制行,我就不会得到精确的副本。如果我对该行进行评论,则该副本在执行时会恢复正常。复制不执行此操作的数组的唯一形式是JSON.parse(JSON.stringify),但我不想依赖它作为方法。我尝试了其他一切,包括lodash的deepClone甚至是一个普通的for循环。同样,当我使用JSON.parse方法时,我的程序按预期执行。任何帮助将不胜感激。

onTableRowDoubleClick(index) {
    console.log('onTableRowDoubleClick');
    let arrayCopy = [];
    arrayCopy = _.cloneDeep(this.state.expandableRowSwitches);
    //let arrayCopy = _.clone(this.state.expandableRowSwitches);
    //let arrayCopy = this.state.expandableRowSwitches.splice(0);
    //let arrayCopy = [...this.state.expandableRowSwitches];
    //let arrayCopy = this.state.expandableRowSwitches.slice(0);
    arrayCopy[index].display = !arrayCopy[index].display;
    return arrayCopy;
}`
javascript arrays reactjs deep-copy
1个回答
0
投票

复制数组中的对象引用原始数组中的对象。您可以使用Object.assign()将每个对象设置为新对象,将属性和值设置为与原始对象相同,以打破相互对象引用。

let arrayCopy = this.state.expandableRowSwitches.map(o => Object.assign({}, o));

const arr = Array({a:1}, {b:2}, {c:3}); // original array

let copy = arr.slice(0); // copy of original array

arr[0].a = 5; // set `"a"` at index 0 of `arr` to `5`

console.log(copy[0].a); // `"a"` at index 0 of `copy` is also set to `5`

copy = arr.map(o => Object.assign({}, o)); // set `o` as a new object

arr[0].a = 1; // set `"a"` at index 0 of `arr` to `5`

console.log(copy[0].a); // `5`,  not set to `1` by `arr` reference
© www.soinside.com 2019 - 2024. All rights reserved.