深拷贝
deepClone
深度克隆一个对象,支持循环引用、Date、RegExp、Map、Set 等类型。
ts
declare function deepClone<T>(obj: T): T参数
| 参数 | 类型 | 说明 |
|---|---|---|
obj | T | 需要克隆的对象 |
返回值:克隆后的新对象,类型与原始对象一致。
示例
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下一步
- 类型检测 — 了解类型判断工具函数