深拷贝拷贝多层,每一级别都拷贝,修改拷贝后的对象,原对象不改变
1. 序列化
// 注意: 如果对象里有函数, undefind, data对象此方法不行
const obj = {
name: 'zs',
family: {
father: 'zs',
mother: 'ls'
},
hobby: ['打游戏', '喝奶茶', '熬夜']
}
// TODO...
const newObj = JSON.parse(JSON.stringify(obj));
// 用来检验是否深拷贝成功
obj.family.father = '王五'
obj.hobby[0] = '睡觉'
console.log(obj);
console.log(newObj);
2.// 封装函数 利用递归遍历每一项
const obj = {
name: 'zs',
family: {
father: 'zs',
mother: 'ls'
},
hobby: ['打游戏', '喝奶茶', '熬夜']
}
const newObj = {}
function deepClone(target, old) {
for (const key in old) {
if (old[key] instanceof Array) {
// 判断是否为数组
// TODO...
// deepCopy 深拷贝; 深复制; 深层复制;
target[key] = []
deepClone(target[key], old[key])
} else if (old[key] instanceof Object) {
// 判断是否为对象
// TODO...
target[key] = []
deepClone(target[key], old[key])
} else {
// TODO...
target[key] = old[key]
}
}
}
deepClone(newObj, obj)
// 用来检验是否深拷贝成功
obj.family.father = '王五'
obj.hobby[0] = '睡觉'
console.log(obj);
console.log(newObj);
3.使用 lodash插件
// 引入lodash
const _ = require('lodash')
const obj = {
name: 'zs',
family: {
father: 'zs',
mother: 'ls'
},
hobby: ['打游戏', '喝奶茶', '熬夜']
}
// TODO...
// 使用lodash
const newObj = _.cloneDeep(obj)
// 下面代码不要动, 用来检验是否深拷贝成功
obj.family.father = '王五'
obj.hobby[0] = '睡觉'
console.log(obj);
console.log(newObj);