我正在尝试找出使函数依赖于更新对象的纯净的最佳方法。是进行深度复制的唯一方法吗?
我知道有关如何复制对象的问题在这里得到了很多回答。我在问是否还有另一种方法可以使此函数保持纯净:
function changeId(item: ObjectWithId): ObjectWithId {
// Not pure
item.id = 1;
return item;
}
是深复制的唯一方法吗?
function changeId(item: ObjectWithId): ObjectWithId {
const newItem = deepCopy(item);
newItem.id = 1;
return newItem;
}
标准是使用扩展运算符
function changeId(item: ObjectWithId): ObjectWithId {
return { ...item, id: 1 };
}
它将所有属性复制到一个新对象,您可以具有属性替代列表。
您不需要深层副本,因为您没有改变原始输入,即使属性是对象,如果您没有改变它们,也可以将它们作为新对象的属性重用。
如果要更改对象属性,则可以为该属性创建新对象
{
...originalObject,
changedProperty: { ...originalObject.changedProperty, propertyToChange: newValue }
}