你理解的深拷贝

源码实现,直接发代码

function deepClone(obj, map=new WeakMap()) {   // WeakMap 弱引用,不用时及时回收
    if(!obj) return obj;
    if(obj instanceof Date) {return new Date(obj)}
    if(obj instanceof RegExp) {return new RegExp(obj)}
    if(typeof(obj) == 'object') {
        let cloneObj = {};
     // 防止循环引用
if(map.get(obj)) { return map.get(obj); } map.set(obj, cloneObj); for(let key in obj) { if(obj.hasOwnProperty(key)) { cloneObj[key] = deepClone(obj[key], map); } } return cloneObj; } else { return obj; } return cloneObj; } let arr = { a: 1, b: 2, c: { d: 5 } } console.log(deepClone(arr))

写完代码,有几点补充下:

  • 对于 数据类型的判断有哪些方法,及相应的优缺点
  1.  typeof
  2.  instanceof
  3.  constructor
  4.  Object.prototype.toString.call(variable) 
  • 对于递归终止条件的判断
  • 什么是弱引用
深度思考,全面总结,综合发展!!
原文地址:https://www.cnblogs.com/strivegys/p/14984922.html