实现深拷贝的几种方式

1.序列化实现深拷贝

//1. 序列化

// 注意: 如果对象里有函数, undefined, data对象此方法不行
 const obj = {
  name: 'zs',
  family: {
    father: 'zs',
    mother: 'ls'
  },
   age:undefined,
    like: function(){
      代码
    },
  hobby: ['打游戏', '喝奶茶', '熬夜']
}
 
 
// TODO...
const j = JSON.parse(JSON.stringify(obj));
// 用来检验是否深拷贝成功
obj.family.father = '王五'
obj.hobby[0] = '睡觉'
console.log(obj);
console.log(j);

2. deepClone函数实现

const obj = {
  name: 'zs',
  family: {
    father: 'zs',
    mother: 'ls'
  },
  hobby: ['打游戏', '喝奶茶', '熬夜']
}
const j = {}
 
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(j, obj)
 
// 用来检验是否深拷贝成功
obj.family.father = '王五'
obj.hobby[0] = '睡觉'
console.log(obj);
console.log(j);

3.引入load第三方插件实现

// 引入lodash
const _ = require('lodash')
 
const obj = {
  name: 'zs',
  family: {
    father: 'zs',
    mother: 'ls'
  },
  hobby: ['打游戏', '喝奶茶', '熬夜']
}
 
// TODO...
// 使用lodash
const j = _.cloneDeep(obj)
 
// 下面代码不要动, 用来检验是否深拷贝成功
obj.family.father = '王五'
obj.hobby[0] = '睡觉'
console.log(obj);
console.log(j);
    </script>

猜你喜欢

转载自blog.csdn.net/qq_69892545/article/details/128803853