015JS深拷贝封装支持string,number,bool,null,undefined,symbol,object,array,date,function

015JS深拷贝封装支持string,number,bool,null,undefined,symbol,object,array,date,function

JS深拷贝可使用第三方库https://www.npmjs.com/package/lodash.clonedeep,也可以手工实现。

JS深拷贝方案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}

JS深拷贝方案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;
}

JS深拷贝方案3:递归函数实现深拷贝2-解决循环引用和symblo类型

function cloneDeep(source, hash = new WeakMap()) {
  if (typeof source !== 'object' || source === null) {
    return source;
  }
  if (hash.has(source)) {
    return hash.get(source);
  }
  const target = Array.isArray(source) ? [] : {};
  Reflect.ownKeys(source).forEach(key => {
    const val = source[key];
    if (typeof val === 'object' && val != null) {
      target[key] = cloneDeep(val, hash);
    } else {
      target[key] = val;
    }
  })
  return target;
}

JS深拷贝方案4:兼容多种数据类型

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
  }
}

深拷贝改进代码(推荐采用)

export function DeepClone(data: any): any {
  if (data && typeof data === 'object') {
    // 处理:object,array,date,function
    switch (Object.prototype.toString.call(data)) {
      case '[object String]':
        return data.toString();
      case '[object Number]':
        return Number(data.toString());
      case '[object Boolean]':
        return new Boolean(data.toString());
      case '[object Date]':
        return new Date(data.getTime());
      case '[object Array]':
        const arr = [];
        for (let i = 0; i < data.length; i++) {
          arr[i] = DeepClone(data[i]);
        }
        return arr;

      // js自带对象或用户自定义类实例
      case '[object Object]':
        const obj: any = {};
        for (let key in data) {
          // 会遍历原型链上的属性方法,可以用obj.hasOwnProperty(prop)来控制
          obj[key] = DeepClone(data[key]);
        }
        return obj;
    }

    // 针对函数的拷贝
    if (typeof data === 'function') {
      let func = data.bind(null);
      func.prototype = DeepClone(data.prototype);
      return func;
    }
  } else {
    // 处理:string,number,bool,null,undefined,symbol
    return data;
  }
}

深拷贝使用方法

import { DeepClone } from '@/utils/DeepClone';
const newObj = DeepClone(obj);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿赛工作室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值