跳到主要内容

手写 JS 深拷贝

浅拷贝和深拷贝

  • 浅拷贝,obj1 = obj2,改变 obj2 的值时,obj1 随之改变
  • 深拷贝,obj1 = deepClone(obj2) ,改变 obj2 的值时,obj1 不会改变
const obj1 = {
age: 20,
name: 'xxx',
address: {
city: 'beijing'
},
arr: ['a', 'b', 'c']
}

深拷贝函数

  • 注意判断值类型和引用类型
  • 注意判断是数组还是对象
  • 递归
/**
* 深拷贝
* @param obj
*/
function deepClone(obj = {}) {
if (typeof obj != 'object' || obj == null) {
// 不是对象或者null,直接返回
return obj
}
let result
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let key in obj) {
// 保证 key 是自身属性而不是原型的属性
if (obj.hasOwnProperty(key)) {
//递归拷贝
result[key] = deepClone(obj[key])
}
}
return result
}

深拷贝通过 JSON 对象的 parse 和 stringify

function deepClone(obj){
let _obj = JSON.stringify(obj),
objClone = JSON.parse(_obj);
return objClone
}

两种拷贝的区别

const obj2 = deepClone(obj1)
obj2.address.city = 'shanghai'
console.log(obj1.address.city) //beijing
const obj3 = obj1
obj3.address.city = 'shenzhen'
console.log(obj1.address.city)//shenzhen