深拷贝的原理
1.先進行 類型判斷?
if(obj==null) return obj;if(obj instanceof RegExp) return new RegExp(obj);if(obj instanceof Date) return new Date(obj);//...if(typeof obj !== 'object') return obj;2. 判斷是 數組還是 對象?
let instance = new obj.constructor;demo?
function deepClone(obj,hash=new WeakMap()) {if(obj==null) return obj;if(obj instanceof RegExp) return new RegExp(obj);if(obj instanceof Date) return new Date(obj);//...if(typeof obj !== 'object') return obj;let instance = new obj.constructor;// if(hash.has(obj)) return hash.get(obj); // hash.set(obj,instance); // for (const key in obj) { // if (obj.hasOwnProperty(key)) { // instance[key] =deepClone(obj[key],hash); // } // }return instance;} console.log(deepClone({a:1,b:2,c:{c:1}})); console.log(deepClone([1,2,3,4]));輸出 :
{} [] 3. 遍歷數組或者數組? ?利用? ?for ..... in?? 4.? 進行拷貝 for (const key in obj) {if (obj.hasOwnProperty(key)) {instance[key] =deepClone(obj[key],hash);}}5.??
if(hash.has(obj)) return hash.get(obj);hash.set(obj,instance);這里是先判斷 是否有被拷貝了 如果被拷貝了 就返回 它
設置映射?
完整demo? : function deepClone(obj,hash=new WeakMap()) {if(obj==null) return obj;if(obj instanceof RegExp) return new RegExp(obj);if(obj instanceof Date) return new Date(obj);//...if(typeof obj !== 'object') return obj;let instance = new obj.constructor;if(hash.has(obj)) return hash.get(obj);hash.set(obj,instance);for (const key in obj) {if (obj.hasOwnProperty(key)) {instance[key] =deepClone(obj[key],hash);}}return instance;} console.log(deepClone({a:1,b:2,c:{c:1}})); console.log(deepClone([1,2,3,4]));輸出 :
?
{ a: 1, b: 2, c: { c: 1 } } [ 1, 2, 3, 4 ]?
轉載于:https://www.cnblogs.com/guangzhou11/p/11328261.html
總結
- 上一篇: 春运学生与民工
- 下一篇: SSRS:使用SQL2008教程学习Re