← 中文资源

简体中文版本

不改动原数组地更新单条记录

用 map 配 spread 只替换命中 id 的那条记录:其余元素保持原引用,未变化的数据不会被误判为变更;直接写 tasks[i] 则原地污染共享数组。

阅读英文原文

实现说明

逻辑集中在函数 completeTask里。

使用要点

  • 直接运行文件,输出会带上标签,比如 original untouched:、t1 same ref:、mutated in place:——输出的每一行都能指回产生它的那次调用。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 completeTask。

入口签名:function completeTask(tasks, id)

核心语句

return tasks.map((task) => (task.id === id ? { ...task, done: true } : task));

代码示例

const tasks = [
  { id: 't1', done: false, title: 'write spec' },
  { id: 't2', done: false, title: 'review pr' },
  { id: 't3', done: false, title: 'ship' },
];

function completeTask(tasks, id) {
  return tasks.map((task) => (task.id === id ? { ...task, done: true } : task));
}

const next = completeTask(tasks, 't2');
console.log(next.map((t) => t.id + ':' + t.done).join(' | '));
console.log('original untouched:', tasks.map((t) => t.done).join(','));

// non-matching elements keep their original references: only t2 is a new object
console.log('t1 same ref:', next[0] === tasks[0], '| t2 new ref:', next[1] !== tasks[1]);

// contrast: writing tasks[1].title directly mutates the shared array in place, and every holder sees the new value at once;
// next[1] is the copy made earlier and still carries the old title
tasks[1].title = 'renamed in place';
console.log('mutated in place:', tasks[1].title, '| copy keeps:', next[1].title);