方式一:通过JSON的stringify与parse方法实现
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]);
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])
执行结果 [object Object]
方式三:使用循环的方式实现
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])