浅拷贝 与 深拷贝 的概念
数组 与 对象 的赋值 就是浅拷贝 , 简单数据类型的赋值 就是 赋值。
如何进行深拷贝
1、对数组进行解构赋值,但是无法满足多维数组的拷贝
const arr = [1, 2, 3]
const arr1 = [...arr]
arr1[1] = 8;
console.log(arr) // [1, 2, 3]
console.log(arr1) // [1, 8, 3]
const arr2 = [1, [2, 3], 4]
const arr3 = [...arr2]
arr3[1][0] = 9;
console.log(arr2) // [1, [9, 3], 4]
console.log(arr3) // [1, [9, 3], 4]
2、利用JSON 函数将 数组或对象 转化成json字符串再返回
这个方法可以解决大部分的深拷贝,但是无法解决 function 拷贝的问题
arr1 = JSON.parse(JSON.stringify(arr)) // 这里就不做代码验证,就是回顾一下 自行验证
3、那么如何解决function深拷贝的问题呢
function deepClone (source) {
// 判断source 是 数组还是对象
const targetObj = source.constructor === Array ? [] : {}
for (let keys in source) {
// source 的属性 是 数组或对象则 进入递归再次执行一次 deepClone
if (source[keys] && typeof source[keys] === 'object') {
// 判断source[keys] 是数组还是对象
targetObj[keys] = source[keys].constructor === Array ? [] : {};
targetObj[keys] = deepClone(source[keys])
} else {
// 如果是常数 就直接赋值
targetObj[keys] = source[keys]
}
}
return targetObj;
}
let obj = {
i: 1,
a: '我是大聪明',
arr: [
1,
2,
3
],
o: {
b: '我是小聪明'
},
// 验证一下是否可以拷贝函数
f: () => {
console.log('你怎么回事')
}
}
newObj = deepClone(obj)
console.log(newObj)
newObj.i = 9;
newObj.arr[0] = 8;
newObj.o.b = '我是大混蛋'
console.log(newObj)
console.log(obj)
obj.f() // 你怎么回事
newObj.f() // 你怎么回事