<aside> <img src="/icons/list-indent_red.svg" alt="/icons/list-indent_red.svg" width="40px" /> TOC

</aside>

你知道吗,JavaScript 中现在有一种原生方法可以对对象进行深度复制?

没错,这个 structuredClone 函数就是内置在 JavaScript 运行时中的:

const calendarEvent = {
  title: "Builder.io Conf",
  date: new Date(123),
  attendees: ["Steve"]
}

// 😍
const copied = structuredClone(calendarEvent)

你是否注意到,在上面的示例中,我们不仅复制了对象,还复制了嵌套数组,甚至复制了日期对象?

而且所有工作都与预期完全一致:

copied.attendees // ["Steve"]
copied.date // Date: Wed Dec 31 1969 16:00:00
cocalendarEvent.attendees === copied.attendees // false

没错, structuredClone 不仅能完成上述功能,还能完成其他功能:

因此,举例来说,这种疯狂甚至会像预期的那样奏效:

const kitchenSink = {
  set: new Set([1, 3, 3]),
  map: new Map([[1, 2]]),
  regex: /foo/,
  deep: { array: [ new File(someBlobData, 'file.txt') ] },
  error: new Error('Hello!')
}
kitchenSink.circular = kitchenSink

// ✅ All good, fully and deeply copied!
const clonedSink = structuredClone(kitchenSink)

为什么不直接解构对象?

需要注意的是,我们说的是深度复制。如果你只需要进行浅层拷贝,也就是不拷贝嵌套对象或数组的拷贝,那么我们可以直接进行对象解构:

const simpleEvent = {
  title: "Builder.io Conf",
}
// ✅ no problem, there are no nested objects or arrays
const shallowCopy = {...calendarEvent}

如果你愿意,也可以选择这些

const shallowCopy = Object.assign({}, simpleEvent)
const shallowCopy = Object.create(simpleEvent)

但是,一旦出现嵌套项,我们就会遇到麻烦: