js深拷贝和浅拷贝

浅拷贝与深拷贝的区别

  1. 解释:
    • 浅拷贝: 只是复制了对象属性或数组元素本身(只是引用地址值)
    • 深拷贝: 不仅复制了对象属性或数组元素本身, 还复制了指向的对象(使用递归)
  2. 举例:
    • 浅拷贝: 只是拷贝了每个 person 对象的引用地址值, 每个 person 对象只有一份
    • 深拷贝: 每个 person 对象也被复制了一份新的

浅拷贝实现

  1. 利用 ES6 语法
function shadowClone1(target) {
  // 如果是数组
  if (target instanceof Array) {
    /*
        使用数组的一些方法
          - return [...target]
          - return target.slice()
          - return [].concat(target)
          - return Array.from(target)
          - return target.filter(value => true)
          - return target.map(item => item)
      */
    return target.reduce((pre, item) => {
      // reduse,不好理解的话用上面的都可以
      pre.push(item)
      return pre
    }, [])
  } else if (target !== null && typeof target === 'object') {
    // 是对象用三点
    return { ...target }
  } else {
    // 如果不是数组或对象, 直接返回
    return target
  }
}

// 测试
const person = { name: '小通', age: 24, hobbies: ['篮球', '跑步'] }
const clonePerson = shadowClone1(person)
// 往克隆的爱好中添加一项
clonePerson.hobbies.push('打代码')
// 结果person和clonePerson中的hobbies都添加了
console.log(person.hobbies) // ['篮球','跑步','打代码']
console.log(clonePerson.hobbies) // ['篮球','跑步','打代码']
  1. 利用 ES5 语法
function shadowClone2(target) {
  // 被处理的目标是数组/对象
  if (
    target instanceof Array ||
    (target !== null && typeof target === 'object')
  ) {
    // 根据target instanceof Array创建类型或对象
    const cloneTarget = target instanceof Array ? [] : {}
    // 循环遍历
    for (const key in target) {
      // 判断一下只拷贝自己身上的属性,忽略原型上的
      if (target.hasOwnProperty(key)) {
        cloneTarget[key] = target[key]
      }
    }
    // 返回
    return cloneTarget
  } else {
    // 如果不是数组或对象直接反回
    return target
  }
}

// 测试
const person = { name: '小通', age: 24, hobbies: ['篮球', '跑步'] }
const clonePerson = shadowClone2(person)
// 往克隆的爱好中添加一项
clonePerson.hobbies.push('打代码')
// 结果person和clonePerson中的hobbies都添加了
console.log(person.hobbies) // ['篮球','跑步','打代码']
console.log(clonePerson.hobbies) // ['篮球','跑步','打代码']

实现深拷贝

  1. 投机取巧版: JSON.stringify 和 JSON.parse–(有问题)

    • 函数属性会丢失

    • 循环引用会出错

    • 代码:

      function deepClone1(target) {
        return JSON.parse(JSON.stringify(target))
      }
      // 测试
      const person = { name: '小通', age: 24, hobbies: ['篮球', '跑步'] }
      const clonePerson = shadowClone1(person)
      // 往克隆的爱好中添加一项
      clonePerson.hobbies.push('打代码')
      // 对象数组没毛病
      console.log(person.hobbies) //  ['篮球', '跑步']
      console.log(clonePerson.hobbies) // ['篮球','跑步','打代码']
      
  2. 基础版本

/* 
      解决了: 函数属性会丢失
      问题: 循环引用会出错
    */
function deepClone2(target) {
  // 被处理的目标是数组/对象
  if (
    target instanceof Array ||
    (target !== null && typeof target === 'object')
  ) {
    // 根据target instanceof Array创建类型或对象
    const cloneTarget = target instanceof Array ? [] : {}
    // 遍历一波
    for (const key in target) {
      // 判断一下只拷贝自己身上的属性,忽略原型上的
      if (target.hasOwnProperty(key)) {
        // 对属性值进行递归处理
        cloneTarget[key] = deepClone2(target[key])
      }
    }
    return cloneTarget
  } else {
    return target
  }
}
// 测试
const person = { name: '小通', age: 24, hobbies: ['篮球', '跑步'] }
const clonePerson = deepClone2(person)
// 往克隆的爱好中添加一项
clonePerson.hobbies.push('打代码')
// 没毛病
console.log(person.hobbies) //  ['篮球', '跑步']
console.log(clonePerson.hobbies) // ['篮球','跑步','打代码']
  1. 加强版本
/* 
      解决了: 函数属性会丢失
      解决: 循环引用会出错    
      解决思路:
          目标: 同一个对旬/数组只能被克隆1次
          创建克隆对象前: 如果克隆对象已经存在, 直接返回
          创建克隆对象后: 保存克隆对象 
          缓存容器结构: Map  key: target, value: cloneTaget
    */
function deepClone3(target, map = new Map()) {
  // 被处理的目标是数组/对象
  if (
    target instanceof Array ||
    (target !== null && typeof target === 'object')
  ) {
    // map中存在对应的克隆对象, 直接将其返回
    let cloneTarget = map.get(target)
    if (cloneTarget) {
      return cloneTarget // 不要对同一个对象进行多次clone
    }
    // 创建克隆对象
    cloneTarget = target instanceof Array ? [] : {}
    // 保存到map容器
    map.set(target, cloneTarget)
    // 遍历一波
    for (const key in target) {
      // 判断一下只拷贝自己身上的属性,忽略原型上的
      if (target.hasOwnProperty(key)) {
        // 对属性值进行递归处理
        cloneTarget[key] = deepClone3(target[key], map)
      }
    }
    return cloneTarget
  } else {
    return target
  }
}
// 测试
const person = { name: '小通', age: 24, hobbies: ['篮球', '跑步'] }
const clonePerson = deepClone3(person)
// 往克隆的爱好中添加一项
clonePerson.hobbies.push('打代码')
// 相当完美
console.log(person.hobbies) //  ['篮球', '跑步']
console.log(clonePerson.hobbies) // ['篮球','跑步','打代码']
  1. 加强版本 2(稍稍优化一点性能)
/* 
        数组: while | for | forEach() 优于 for-in | keys()&forEach() 
        对象: for-in 与 keys()&forEach() 差不多
    */
function deepClone4(target, map = new Map()) {
  // 被处理的目标是数组/对象
  if (
    target instanceof Array ||
    (target !== null && typeof target === 'object')
  ) {
    // map中存在对应的克隆对象, 直接将其返回
    let cloneTarget = map.get(target)
    if (cloneTarget) {
      return cloneTarget // 不要对同一个对象进行多次clone
    }
    // 创建克隆对象
    if (target instanceof Array) {
      // 数组使用 forEach
      cloneTarget = []
      // 保存到map容器
      map.set(target, cloneTarget)
      // 向数组添加元素
      target.forEach((item, index) => {
        // 对属性值进行递归处理
        cloneTarget[index] = deepClone4(item, map)
      })
    } else {
      cloneTarget = {}
      // 保存到map容器
      map.set(target, cloneTarget)
      // 向对象添加属性
      for (const key in target) {
        // 数组使用 for-in
        if (target.hasOwnProperty(key)) {
          // 对属性值进行递归处理
          cloneTarget[key] = deepClone4(target[key], map)
        }
      }
    }

    return cloneTarget
  } else {
    return target
  }
}
// 测试
const person = { name: '小通', age: 24, hobbies: ['篮球', '跑步'] }
const clonePerson = deepClone4(person)
// 往克隆的爱好中添加一项
clonePerson.hobbies.push('打代码')
// 完美
console.log(person.hobbies) //  ['篮球', '跑步']
console.log(clonePerson.hobbies) // ['篮球','跑步','打代码']

完…

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值