深拷贝的实现

2021-08-28  本文已影响0人  townYouth
function deepClone(source,uniqueList){
     if(!(typeof source === 'object' && source != null)) return source;

     if(!uniqueList) uniqueList = [];    //   初始化数据

     let target = Array.isArray(source) ? [] : {};

     let uniqueData = null
     let index = uniqueList.findIndex(item => {
         return item.source === source
     })
     if(index !== -1) return uniqueList[index].target;


     uniqueList.push({
         source:source,
         target:target
     });

     for(let key in source){
         if(Object.prototype.hasOwnProperty.call(source,key)){
             if(typeof source[key] === 'object' && source[key] != null){
                 target[key] = deepClone(source[key], uniqueList)      //   传入数组
             }else{
                 target[key] = source[key];
             }
         }
     }
     return target;
 }
上一篇 下一篇

猜你喜欢

热点阅读