js 新版深度拷贝

似水流年ii / 2024-09-25 / 原文

旧的

1、JSON.parse(JSON.stringify(obj))

简单易行,只能处理基本的对象、数组

2、递归

3、第三方库,如 lodash 的 _.cloneDeep 方法

4、现代深拷贝 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

const clonedSink = structuredClone(kitchenSink)