【发布时间】:2021-06-01 00:51:54
【问题描述】:
我正在尝试在数组元素中复制数组并根据我的需要进行操作。
this.question?.labels.forEach((element) => {
element["options"] = [...this.question?.options]; // I've tried json.stringify() as well but not worked
element["options"].forEach(e => {
e.checked = this.question?.userAnswers.find(i => e.key === i.value && element.key === i.key) ? true : false;
});
});
我每次都使用[...this.question?.options] 来获取选项的新副本。但它总是在每个元素中保存数组的最后一个值
https://stackblitz.com/edit/pass-array-by-value?file=src%2Fapp%2Fapp.component.ts
【问题讨论】:
-
这能回答你的问题吗? Deep copying objects in Angular
-
扩展运算符
...只会制作数组的浅副本。作为对象的数组元素仍将保持其引用并将被变异。您将需要一份 deep 副本。查看重复链接。 -
我也尝试过 JSON.parse(JSON.stringify(Object)) ,但它不起作用。我创建了 stackblitz 链接供您参考,如果您想查看
标签: javascript arrays angular typescript deep-copy