// 判断是否是某类型 const isType = (obj, type) => { if (typeof obj !== 'object') return false; const typeString = Object.prototype.toString.call(obj); let flag; switch (type) { case 'Array': flag = typeString === '[object Array]'; break; case 'Date': flag = typeString === '[object Date]'; break; case 'RegExp': flag = typeString === '[object RegExp]'; break; default: flag = false; } return flag; }; // 获取到正则修饰符 const getRegExp = re => { var flags = ''; if (re.global) flags += 'g'; if (re.ignoreCase) flags += 'i'; if (re.multiline) flags += 'm'; return flags; }; // 深度克隆 const deepClone = parent => { // 旧对象 :新对象 map let _map = new WeakMap(); const _clone = parent => { if (parent === null) return null; if (typeof parent !== 'object') return parent; if(_map.get(parent)){ return _map.get(parent) } let newParent; if (isType(parent, 'Array')) { // 对数组做特殊处理 newParent = []; } else if (isType(parent, 'RegExp')) { // 对正则对象做特殊处理 newParent = new RegExp(parent.source, getRegExp(parent)); if (parent.lastIndex) newParent.lastIndex = parent.lastIndex; } else if (isType(parent, 'Date')) { // 对Date对象做特殊处理 newParent = new Date(parent.getTime()); } else { // 处理对象原型 newParent = Object.create(parent.__proto__); } _map.set(parent, newParent); for (let i in parent) { // 递归 newParent[i] = _clone(parent[i]); } return newParent; }; return _clone(parent); };
标签:map,newParent,return,克隆,parent,flag,深度,const,拷贝 From: https://www.cnblogs.com/shaoyunfeng93/p/16732054.html