js 深拷贝
转自:https://github.com/shfshanyue/Daily-Question/issues/203#issuecomment-888238489
/** * 深拷贝关注点: * 1. JavaScript内置对象的复制: Set、Map、Date、Regex等 * 2. 循环引用问题 * @param {*} object * @returns */ function deepClone(source, memory) { const isPrimitive = (value) => { return /Number|Boolean|String|Null|Undefined|Symbol|Function/.test(Object.prototype.toString.call(value)); } let result = null; memory || (memory = new WeakMap()); // 原始数据类型及函数 if (isPrimitive(source)) { console.log('current copy is primitive', source); result = source; } // 数组 else if (Array.isArray(source)) { result = source.map(value => deepClone(value, memory)); } // 内置对象Date、Regex else if (Object.prototype.toString.call(source) === '[object Date]') { result = new Date(source); } else if (Object.prototype.toString.call(source) === '[object Regex]') { result = new RegExp(source); } // 内置对象Set、Map else if (Object.prototype.toString.call(source) === '[object Set]') { result = new Set(); for (const value of source) { result.add(deepClone(value, memory)); } } else if (Object.prototype.toString.call(source) === '[object Map]') { result = new Map(); for (const [key, value] of source.entries()) { result.set(key, deepClone(value, memory)); } } // 引用类型 else { if (memory.has(source)) { result = memory.get(source); } else { result = Object.create(null); memory.set(source, result); Object.keys(source).forEach(key => { const value = source[key]; result[key] = deepClone(value, memory); }); } } return result; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
2018-08-10 小程序渲染html的两种方法