深拷贝实现~(解决了循环引用和symbol问题)

对循环引用解决的方案其实很简单
就是使用哈希表
其实就是循环检测,我们设置一个数组或者哈希表存储已拷贝过的对象,当检测到当前对象已存在于哈希表中时,取出该值并返回即可。

function cloneDeep4(source, hash = new WeakMap()) {

    if (!isObject(source)) return source; 
    if (hash.has(source)) return hash.get(source); // 查哈希表
      
    let target = Array.isArray(source) ? [] : {};
    hash.set(source, target); // 哈希表设值
    
    let symKeys = Object.getOwnPropertySymbols(source); // 查找
    if (symKeys.length) { // 查找成功   
        symKeys.forEach(symKey => {
            if (isObject(source[symKey])) {
                target[symKey] = cloneDeep4(source[symKey], hash); // 传入哈希表
            } else {
                target[symKey] = source[symKey];
            }    
        });
    }
    
    for(let key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
            if (isObject(source[key])) {
                target[key] = cloneDeep4(source[key], hash); 
            } else {
                target[key] = source[key];
            }
        }
    }
    return target;
}

你可能感兴趣的:(深拷贝实现~(解决了循环引用和symbol问题))