一、JSON.parse(JSON.stringify))
const obj = {
a:1,
b:['e','f','g'],
c:{h:20},
// JSON不能克隆方法
d:function(){}
}
console.log(obj) // {"a": 1,"b": ["e","f","g"],"c": {"h": 20},"d": function()}
// 循环引用
obj.b.push(obj.c)
obj.c.j = obj.b
console.log(deepClone1(obj)) // {"a": 1,"b": ["e","f","g"],"c": {"h": 20}}
function deepClone1(target){
let str = JSON.parse(JSON.stringify(target))
return str
}
缺点:
1. JSON不能克隆方法
2.循环引用报错

二、递归拷贝
function deepClone1(target) {
if (typeof(target) === 'object' && target !== null) {
const result = Array.isArray(target) ? [] : {}
for (let key in target) {
if (target.hasOwnProperty(key)) {
result[key] = deepClone1(target[key])
}
}
return result
} else {
return target
}
}
const obj = {
a:1,
b:['e','f','g'],
c:{h:20},
// JSON不能克隆方法
d:function(){}
}
obj.b.push(obj.c)
obj.c.j = obj.b
console.log(obj) // {"a": 1,"b": ["e","f","g"],"c": {"h": 20},"d": function()}
const result = deepClone1(obj)
result.c.h = 2300
console.log(result) // {"a": 1,"b": ["e","f","g"],"c": {"h": 2300},"d": function()}
三、递归拷贝(解决循环引用报错)
function deepClone1(target,map=new Map()) {
if (typeof(target) === 'object' && target !== null) {
let cache = map.get(target)
if(cache) return cache
const result = Array.isArray(target) ? [] : {}
map.set(target,result)
for (let key in target) {
if (target.hasOwnProperty(key)) {
result[key] = deepClone1(target[key],map)
}
}
return result
} else {
return target
}
}
const obj = {
a:1,
b:['e','f','g'],
c:{h:20},
// JSON不能克隆方法
d:function(){}
}
obj.b.push(obj.c)
obj.c.j = obj.b
console.log(obj) // {"a": 1,"b": ["e","f","g"],"c": {"h": 20},"d": function()}
const result = deepClone1(obj)
result.c.h = 2300
console.log(result) // {"a": 1,"b": ["e","f","g"],"c": {"h": 2300},"d": function()}
四、优化for in(解决循环引用报错)
function deepClone1(target,map=new Map()) {
if (typeof(target) === 'object' && target !== null) {
let cache = map.get(target)
if(cache) return cache
let isArray = Array.isArray(target)
const result = isArray ? [] : {}
map.set(target,result)
if(isArray){
target.forEach((item,index) =>{result[index] = deepClone1(item,map)})
}else{
Object.keys(target).forEach(key =>{result[key] = deepClone1(target[key],map)})
}
return result
} else {
return target
}
}
const obj = {
a:1,
b:['e','f','g'],
c:{h:20},
// JSON不能克隆方法
d:function(){}
}
obj.b.push(obj.c)
obj.c.j = obj.b
console.log(obj) // {"a": 1,"b": ["e","f","g"],"c": {"h": 20},"d": function()}
const result = deepClone1(obj)
// result.c.h = 2300
console.log(result) // {"a": 1,"b": ["e","f","g"],"c": {"h": 2300},"d": function()}