1.为什么要使用深拷贝?
我们希望在改变新的数组(对象)的时候,不改变原数组(对象)
2.深拷贝和浅拷贝的区别
1.浅拷贝: 将原对象或原数组的引用直接赋给新对象,新数组,新对象/数组只是原对象的一个引用
2.深拷贝: 创建一个新的对象和数组,将原对象的各项属性的“值”(数组的所有元素)拷贝过来,是“值”而不是“引用”
B复制A,A变,B变,浅拷贝。
B复制A,A变,B不变,深拷贝。
<script>
let a = 1;
b = a;
a = 0;
console.log(b)
let obj = { name: '1', id: "2" };
let obj2 = obj;
console.log(obj2)
obj.name = '2'
console.log(obj2)
</script>
平常的a赋值给b,a变,b并不会变。而对于对象obj2,这种简单的赋值,obj 变,obj2变,就是浅拷贝了。
这是为啥呢?这就要我们从数据类型说起了。。。。
3.基本数据类型和引用数据类型
基本数据类型有:string,boolean,null,number,undefined,symbol(ES6),BigInt(ES10)
而引用数据类型:object,list,function。 他们之间的赋值方式是不一样的。
4.数组的浅拷贝(只拷贝第一级数组元素)
1 .直接遍历
var array = [1, 2, 3, 4];
function copy(array) {
let newArray = []
for (let item of array) {
newArray.push(item);
}
return newArray;
}
var copyArray = copy(array);
copyArray[0] = 100;
console.log(array); // [1, 2, 3, 4]
console.log(copyArray); // [100, 2, 3, 4]
该方法不做解释
2 . slice()
var array = [1, 2, 3, 4];
var copyArray = array.slice();
copyArray[0] = 100;
console.log(array); // [1, 2, 3, 4]
console.log(copyArray); // [100, 2, 3, 4]
slice() 方法返回一个从已有的数组中截取一部分元素片段组成的新数组(不改变原来的数组!)
用法:array.slice(start,end) start表示是起始元素的下标, end表示的是终止元素的下标
当slice()不带任何参数的时候,默认返回一个长度和原数组相同的新数组
5.对象的浅拷贝
1 .直接遍历
2 .ES6的Object.assign
var obj = {
name: '张三',
job: '学生'
}
var copyObj = Object.assign({}, obj);
copyObj.name = '李四';
console.log(obj); // {name: "张三", job: "学生"}
console.log(copyObj); // {name: "李四", job: "学生"}
Object.assign:用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target),并返回合并后的target
用法: Object.assign(target, source1, source2); 所以 copyObj = Object.assign({}, obj); 这段代码将会把obj中的一级属性都拷贝到 {}中,然后将其返回赋copyObj
3 .ES6扩展运算符:
var obj = {
name: {
firstName: '张',
lastName: '三'
},
job: '学生'
}
var copyObj = Object.assign({}, obj)
copyObj.name.lastName = '三三';
console.log(obj.name.lastName); //
console.log(copyObj.name.lastName); //
深拷贝
有没有更强大一些的解决方案呢?使得我们能够
1 .不仅拷贝第一层级,还能够拷贝数组或对象所有层级的各项值
2 . 不是单独针对数组或对象,而是能够通用于数组,对象和其他复杂的JSON形式的对象
1. 先转换成字符串,在转换成(数组/对象)JSON.parse(JSON.stringify(XXXX))
var array = [
{ number: 1 },
{ number: 2 },
{ number: 3 }
];
var str = JSON.stringify(array);
var copyArray = JSON.parse(str)
copyArray[0].number = 100;
console.log(array); // [{number: 1}, { number: 2 }, { number: 3 }]
console.log(copyArray); // [{number: 100}, { number: 2 }, { number: 3 }]
let obj = { name: '1', id: '2', son: undefined, sis: Symbol(1), fun: function () { return 1 } }
let obj1 = JSON.parse(JSON.stringify(obj))
console.log(obj)
//fun: ƒ id: "2" name: "2" sis: Symbol(1) son:undefined
console.log(obj1)
obj.name = '2'
console.log(obj)
console.log(obj1)
缺点非常明显,无法copy函数,undefined和symbol,同样也无法解决循环引用的对象。
2 .手动写递归
function deepClone(obj = {}) {
if (typeof obj !== 'object' || obj == null) {
// 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
}