function deepClone(obj, hash = new WeakMap()) { if (Object(obj) !== obj) return obj; // 原始类型直接返回 if (hash.has(obj)) return hash.get(obj); // 防止循环引用

let cloneObj;

if (obj instanceof Date) { cloneObj = new Date(obj.getTime()); // 处理Date类型 } else if (obj instanceof RegExp) { cloneObj = new RegExp(obj.source, obj.flags); // 处理RegExp类型 } else if (obj instanceof Function) { cloneObj = function() { return obj.apply(this, arguments) }; // 处理Function类型 } else if (obj instanceof Set) { cloneObj = new Set([...obj].map(item => deepClone(item, hash))); // 处理Set类型 } else if (obj instanceof Map) { cloneObj = new Map([...obj].map(([key, value]) => [deepClone(key, hash), deepClone(value, hash)])); // 处理Map类型 } else if (Array.isArray(obj)) { cloneObj = obj.map(item => deepClone(item, hash)); // 处理Array类型 } else if (typeof obj === 'object' && obj !== null) { cloneObj = {}; hash.set(obj, cloneObj); Object.keys(obj).forEach(key => { cloneObj[key] = deepClone(obj[key], hash); // 处理Object类型 }); }

return cloneObj; }

JavaScript 深拷贝函数:深度优先遍历,兼容各种数据类型

原文地址: https://www.cveoy.top/t/topic/lMoV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录