js深拷贝与循环引用


function deepCopy(target) {
    var arr = []; // use array store the used refrence, and avoid repeat
    return _deepCopy(target);
    
    function _deepCopy(target) {
        let result = {};
        for (let k in target) {
            if (target.hasOwnProperty(k)) {
                if (target[k] && typeof target[k] === 'object') {
                    if ((arr.filter(v=>v === target[k])).length === 0) {
                        arr.push(target[k]);
                        result[k] = _deepCopy(target[k]);
                    }

                } else {
                    result[k] = target[k];
                }
            }
        }
        return result;
    }
}

// test code
var a = {
    n: 1,
    m: 2
};
var b = {
    m: 1,
    n: 2
};
a.b = b;
b.a = a;
var c = deepCopy(a);