【问题标题】:Javascript Array Copy getting corruptedJavascript 数组副本损坏
【发布时间】:2017-04-19 00:59:58
【问题描述】:

我有一组处于 React 状态的对象: this.state.expandableRowSwitches 是一个对象数组:

{显示:假,选择:假,重影:假}

当我尝试制作数组的副本来操作它(深或浅)时,如果我在复制行之后使用操作数组的特定索引的行,我不会得到精确的副本。如果我注释掉该行,则副本在执行时会恢复到完美状态。唯一不这样做的复制数组的单一形式是 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;
}`

【问题讨论】:

  • 我不确定你的问题,但你试过Array.from()吗?
  • 我刚刚尝试过,arrayCopy = Array.from(this.state.expandableRowSwitches) 给了我同样的问题。所有开关都转换为真(它们开始为假)。当只有一行应该扩展时,这具有我所有行扩展的效果(通过仅针对该单个索引将显示开关设置为 true)。当我使用 JSON.parse(JSON.stringify... 作为复制方法时,一切都按预期工作。虽然我不想依赖该复制方法

标签: javascript arrays reactjs deep-copy


【解决方案1】:

复制数组中的对象引用原始数组中的对象。您可以使用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

【讨论】:

  • 谢谢!那行得通。虽然我不明白为什么 lodash 的 _.cloneDeep(this.state.expandableRowSwitches) 不起作用,因为该方法应该返回没有引用的数组的深层副本......
  • @JaredBoice 不确定lodash_.cloneDeep 方法。文档是否提供返回值的详细信息?
  • 它说:“返回深度克隆值。”我看到 Object.assign 只执行一个浅拷贝(在这种情况下,我假设它是有效的,因为每个数组元素中的对象不会深入到另一个层次?)......如果有多个层次的情况,你会推荐什么对象中的对象?再次感谢,非常感谢
  • 您可以使用迭代、递归或调度来调用Object.assign() 在具有引用对象值的属性的对象。
  • 我想我明白了。我在做 arrayCopy = _.cloneDeep(this.state.expandableRowSwitches) 而我应该做 arrayCopy = this.state.expandableRowSwitches.map(o => _.cloneDeep(o));
猜你喜欢
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多