深拷贝与浅拷贝
浅拷贝:主要是引用类型的的值是赋值一个堆地址,浅拷贝是赋值同一个地址,从而改变时会同时改变
深拷贝:将其复制过来,并创建一个新的地址,从而互不干扰
深拷贝的方法
- JSON转换
var deepObj= JSON.parse(JSON.stringify(obj))
- 递归函数
const obj1 = {
a: 1,
b: 2,
fun: function() {
console.log(2222);
},
c: {
c1: 3,
c2: 4
}
}
const obj2 = obj1;
const obj3 = deepClone(obj1);
obj2.a = '2a';
obj3.a = '3a';
console.log(obj1.a); // 2a
console.log(obj2.a); // 2a
console.log(obj3.a); // 3a
function deepClone(obj) {
// obj = null 并且不是对象或数组的时候直接返回为空
if (typeof obj !== 'object' || obj == 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;
}