题解 | #深拷贝函数实现#

深拷贝

http://www.nowcoder.com/practice/70ca77b52d424ced8ebb348cd77c1dc5

const _completeDeepClone = (target, map = new Map()) => {   // map 用来记录是否已经被拷贝过
    // 补全代码
    if(typeof target == "object" &&  target !== null){       
        if(/^(Function|RegExp|Date|Set|Map)$/i.test(target.constructor.name)) return new target.constructor(target);  //进行深拷贝,不能传递地址
        if(map.get(target)) return map.get(target);                       // 已经遍历到了,直接返回结果
        map.set(target,true);                                             // 还未遍历过,设置为 true
        let collect = Array.isArray(target) ? [] : {};      
        for( prop in target){                                             // 开始遍历
          if(target.hasOwnProperty(prop))
            collect[prop] = _completeDeepClone(target[prop],map);
        }
        return collect;
    }else{
      	return target
    }
}
全部评论

相关推荐

06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
实习吐槽大会
点赞 评论 收藏
分享
评论
5
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务