方式一:通过JSON的stringify与parse方法实现
let obj = {a: 1, b: [{c: 2, d: 3}, {e: 4, f: 5}], g: 6}
let result = JSON.parse(JSON.stringify(obj));
console.log(result, obj, result === obj);
console.log(result.b, obj.b, result.b === obj.b);
console.log(result.b[0], obj.b[0], result.b[0] === obj.b[0]);
执行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/0da66daf426802f6b9ccef6a48aedd96.png)
方式二:通过递归的方法实现
const deepCopy = (obj) => {
let target = null
if(typeof obj === 'object'){
if(Array.isArray(obj)){ //数组
target = [];
obj.forEach(item => {
target.push(deepCopy(item));
})
}else if(obj){
target = {}
let objKeys = Object.keys(obj);
objKeys.forEach(key => {
target[key] = deepCopy(obj[key]);
})
}else{
target = obj
}
}else{
target = obj;
}
return target
}
let obj = {a: 1, b: [{c: 2, d: 3}, {e: 4, f: 5}], g: 6}
let result = deepCopy(obj);
console.log(result, obj, result === obj)
console.log(result.b, obj.b, result.b === obj.b)
console.log(result.b[0], obj.b[0], result.b[0] === obj.b[0])
执行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/36b7d8afcb4aa074121307e5f38f104a.png)
方式三:使用循环的方式实现
const deepCopy = (obj) => {
//浅拷贝子节点
let handleChild = (child) => {
if(typeof child === 'object'){
if(Array.isArray(child)){ // 数组
return [...child]
}else if(child){ // 对象
return {...child}
}else{ // null
return child
}
}else{ // 值类型
return child
}
}
let arr = [];
let target = {result: obj};
let current = target;
while(current){
if(typeof current === 'object'){
if(Array.isArray(current)){ //数组
current.forEach((item, index) => {
let child = handleChild(item)
current[index] = child;
arr.push(child);
})
}else if(current){ //对象
let objKeys = Object.keys(current);
objKeys.forEach(key => {
let child = handleChild(current[key]);
current[key] = child;
arr.push(child);
})
}else{ //null
temp = current;
}
}
current = arr.shift()
}
return target.result
}
let obj = {a: 1, b: [{c: 2, d: 3}, {e: 4, f: 5}], g: 6}
let result = deepCopy(obj);
console.log(result, obj, result === obj)
console.log(result.b, obj.b, result.b === obj.b)
console.log(result.b[0], obj.b[0], result.b[0] === obj.b[0])
执行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/e6019fabf800d9e10ce2884f436f7a0b.png)