使用javascript进行深拷贝

浅拷贝是创建一个新对象,这个对象有着原始对象属性值的拷贝。如果属性是基本类型,拷贝的就是基本类型的值,如果属性是引用类型,拷贝的是内存地址 。其中一个对象改变了对象的值,就会影响到另一个对象的值。


深拷贝是将一个对象从内存中完整的拷贝一份出来,从堆内存中开辟一个新的区域存放新对象,且修改新对象不会影响原对象。

1、JSON.parse(JSON.stringify(obj))

let a = {a:1,b:2}
let b = JSON.parse(JSON.stringify(a))
a.a = 11
console.log(a)//{a:1,b:2}
console.log(b)//{a:11,b:2}

2、普通递归函数

function deepClone(source) {
  if (typeof source !== 'object' || source == null) {
    return source;
  }
  const target = Array.isArray(source) ? [] : {};
  for (const key in source) {
    if (Object.prototype.hasOwnProperty.call(source, key)) {
      if (typeof source[key] === 'object' && source[key] !== null) {
        target[key] = deepClone(source[key]);
      } else {
        target[key] = source[key];
      }
    }
  }
  return target;
}

3、兼容多种数据类型

const deepClone = (source, cache) => {
  if(!cache){
    cache = new Map() 
  }
  if(source instanceof Object) { // 不考虑跨 iframe
    if(cache.get(source)) { return cache.get(source) }
    let result 
    if(source instanceof Function) {
      if(source.prototype) { // 有 prototype 就是普通函数
        result = function(){ return source.apply(this, arguments) }
      } else {
        result = (...args) => { return source.call(undefined, ...args) }
      }
    } else if(source instanceof Array) {
      result = []
    } else if(source instanceof Date) {
      result = new Date(source - 0)
    } else if(source instanceof RegExp) {
      result = new RegExp(source.source, source.flags)
    } else {
      result = {}
    }
    cache.set(source, result)
    for(let key in source) { 
      if(source.hasOwnProperty(key)){
        result[key] = deepClone(source[key], cache) 
      }
    }
    return result
  } else {
    return source
  }
}

4、jquery.extend()方法

可以使用$.extend进行深拷贝
$.extend(deepCopy, target, object1, [objectN])//第一个参数为true,就是深拷贝

let a = {
    a: 1,
    b: { d:8},
    c: [1, 2, 3]
};
let b = $.extend(true, {}, a);
console.log(a.b.d === b.b.d); // false

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值