You need to enable JavaScript to run this app. 如何在TypeScript中不使用NgRx实现对象数组的不可变管理?
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中不使用NgRx实现对象数组的不可变管理?

问题成因

  • 直接修改item1Find的属性破坏了不可变性规则:item1Find是原数组内对象的引用,修改它的属性会同步改动原数组中对应对象的属性,本质上还是在改原数据。
  • 数组更新逻辑错误:[...items, item1Find]是往现有数组末尾追加元素,不是替换原有符合条件的元素,最终数组就会同时存在原位置的对象和新追加的同一个引用对象,所以出现两条相同内容。

不可变操作的核心要求是永远不修改原引用指向的数据,所有改动都要生成全新的对象/数组

正确实现代码

let items: Array<{n: string}> = [];
const item1 = { n: 'toto' };
// 新增元素
items = [...items, item1];

// 不可变更新元素
const targetIndex = items.findIndex(v => v.n === 'toto');
if (targetIndex > -1) {
  // 生成全新的修改后对象,不改动原对象
  const updatedItem = { ...items[targetIndex], n: 'titi' };
  // 替换数组对应位置的元素,生成全新数组
  items = [
    ...items.slice(0, targetIndex),
    updatedItem,
    ...items.slice(targetIndex + 1)
  ];
}

// 删除元素的不可变操作可参考:
// items = [...items.slice(0, targetIndex), ...items.slice(targetIndex + 1)]

console.log('items', JSON.stringify(items)); // 输出 [{"n":"titi"}]

内容的提问来源于stack exchange,提问作者duke666

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 15:36:06