1
let a ={}
let b ={}
a.b = b
b.a = a

function deepClone(obj, hash = new WeakMap()) {
    console.log(hash)
    if (hash.has(obj)) {
        // 如果已经拷贝过该对象,直接返回
        return hash.get(obj);
    }
    if (typeof obj === 'object') {
        // 如果不是对象或者为null,直接返回
        var result = obj instanceof Array ? [] : {};
        hash.set(obj, result);
    }

    // 递归拷贝对象属性
    for(let i in obj){
        result[i]=deepClone(obj[i],hash)
    }
    return result;
}

let result=deepClone(a)
console.log(result)

Using WeakMap in the deepClone function can work correctly,but if think about the logic behind it, the function may encounter an endless loop

enter image description here

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • This post might help : [Detecting and fixing circular references in JavaScript](https://stackoverflow.com/questions/14962018/detecting-and-fixing-circular-references-in-javascript) – EricLavault Jun 04 '23 at 16:07
  • 1
    What is the question? – Pointy Jun 04 '23 at 16:20
  • "*if think about the logic behind it, the function may encounter an endless loop*" - no, it cannot. Or at least it doesn't in the example you've given, as you can easily try out by executing the code snippet. Please explain your thought on why you think it might enter an infinite loop, and try to test your hypothesis by building an input that would trigger this behaviour – Bergi Jun 04 '23 at 17:06
  • The recursion works like the image I provided, However, even after executing Step 3, we still cannot obtain the precise numerical value of "deepClone()".Given this premise, it is not possible to obtain the "result" – DingdongChicken Jun 05 '23 at 05:29

0 Answers0