深拷贝

deepClone

深度克隆一个对象,支持循环引用、DateRegExpMapSet 等类型。

ts
declare function deepClone<T>(obj: T): T

参数

参数类型说明
objT需要克隆的对象

返回值:克隆后的新对象,类型与原始对象一致。

示例

tsx
import { deepClone } from 'vitarx'

const original = {
  name: 'Vitarx',
  version: 4,
  tags: ['框架', '响应式'],
  meta: { date: new Date() }
}

// 深拷贝,修改副本不会影响原始对象
const copy = deepClone(original)
copy.name = 'Copy'
copy.tags.push('工具')

console.log(original.name) // 'Vitarx'
console.log(original.tags) // ['框架', '响应式']

支持循环引用:

tsx
import { deepClone } from 'vitarx'

const obj = { name: '循环' }
obj.self = obj // 自引用

const copy = deepClone(obj)
console.log(copy === copy.self) // true

下一步