我有一个对象,其结构类似于data.edit.lstAnnotation.lstComments
,并带有
...
lstAnnotation?: AnnotationInterface;
...
export interface AnnotationInterface {
lstComments: CommentList;
}
export class CommentList {
[key: string]: CommentEntity;
}
...
据我所知,函数Object.assign()
进行浅表复制。这意味着不会复制内容,并且会保留引用。我有一个类似的功能
Object.keys(this.data.edit.lstAnnotation.lstComments).map((key: string) => {
const newEntity = {...this.data.edit.lstAnnotation.lstComments[key]};
delete newEntity.cur; // <<<<----------------- [1]
if (newEntity.add && newEntity.add.trim().length === 0) {
delete newEntity.add; // <<<<-------------- [2]
}
return JSON.stringify(newEntity);
}).join();
这是一个很好的字符串。据我了解,我创建了内容的shallow copy,然后删除(delete
)属性。我的问题是,为什么delete
不适用于原始列表(data.edit.lstAnnotation.lstComments
)?
[我仍然在data.edit.lstAnnotation.lstComments
项中带有key
cur
,例如data.edit.lstAnnotation.lstComments['abc'].cur
==> object....
我对目前的情况感到非常满意。但是,如果我从复制的对象中删除并且原始对象没有更新,我会说这是一个深层副本。那么,我的错误在哪里?
这里有一些示例代码演示了核心问题:
const array = [1, 2, 3];
const original = {a: array, b: 4};
const copy = {};
Object.assign(copy, original);
delete copy.a;
会发生什么:
array1
保留对其的引用。a
保留对数组的引用,属性b
保留值4,original
保留对新对象的引用。copy
拥有对该对象的引用。Object.assign
将对象original
引用的对象复制到对象copy
的引用中。这是一个浅表副本,因此copy.a
现在是对与original.a
相同的数组的引用;没有创建数组的副本。a
的对象的copy
属性被删除,因此该对象不再具有名为a
的属性。引用的对象original
仍然具有自己的名为a
的属性,因为它是一个不同的对象。它可以帮助您通过stepping through the execution using the excellent Javascript Tutor tool来理解,它以可视方式显示了在执行每一行时程序状态的变化。