Created
August 15, 2019 09:39
-
-
Save llccing/bb5f9b64a4df586ab8188d42c955f307 to your computer and use it in GitHub Desktop.
深克隆
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepCopy(target) { | |
let copyed_objs = []; //此数组解决了循环引用和相同引用的问题,它存放已经递归到的目标对象 | |
function _deepCopy(target) { | |
if (typeof target !== 'object' || !target) { | |
return target; | |
} | |
for (let i = 0; i < copyed_objs.length; i++) { | |
if (copyed_objs[i].target === target) { | |
return copyed_objs[i].copyTarget; | |
} | |
} | |
let obj = {}; | |
if (Array.isArray(target)) { | |
obj = []; //处理target是数组的情况 | |
} | |
copyed_objs.push({ target: target, copyTarget: obj }); | |
Object.keys(target).forEach((key) => { | |
if (obj[key]) { | |
return; | |
} | |
obj[key] = _deepCopy(target[key]); | |
}); | |
return obj; | |
} | |
return _deepCopy(target); | |
} | |
// 测试代码 | |
let obj = { | |
a: 12, | |
b: [123123, 123123], | |
c: function() { | |
let a = 0; | |
}, | |
d: { | |
a: { f: 'asdfasdf' }, | |
g: 1 | |
}, | |
}; | |
let b = deepCopy(obj); | |
console.log(obj); | |
console.log(b); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment