JavaScript _ 对象深拷贝 | 深克隆

/**
 * 对象深拷贝工具类
 * 拦截器:filter 参数[key, value, ang(fn)]
 */
export default class OUtil {
    constructor(...fn) {
        this.filters = fn
    }

    agn(source) {
        // 判空
        if (source == null) return null

        // 判断是否对象类型
        if (typeof source === 'object') {
            // 是否数组
            if (Array.isArray(source)) {
                let result = []
                for (let x in source) {
                    result.push(this.agn(source[x]))
                }
                return result
            }
            // 是否正则对象
            if (source.constructor === RegExp) return source

            // 为 map 类型
            let result = {}
            for (let key in source) {
                for (let index in this.filters) {
                    // 拦截器不是一个函数
                    if (!(typeof this.filters[index] === 'function')) {
                        result[key] = this.agn(source[key])
                    }
                    // 执行拦截器
                    let data = this.filters[index](key, source[key], this.agn)
                    if (data === '$ignore$') {
                        continue
                    }
                    // 没有结果返回时
                    result[key] = (typeof data === 'undefined') ? this.agn(source[key]) : data
                }
            }
            return result
        }
        // 不是对象则直接返回
        else {
            return source;
        }
    }
}

项目所用 :

src  /  views  /  preview  /  index.vue

<script>
export default {
  name: 'Preview',

  data() {
    return {

    }
  },

  created() {
    let _list = this.$store.state.saveData
    let newArr = []
    _list.map((item) => {
      newArr.push(this.deepClone(item))    // 数组进行深拷贝
    )}
    this.data = newArr
  },

  methods: {
    // 对象深度克隆
    deepClone(obj) {
      let newObj = {}
      if (typeof obj === 'object') {
        // 数组或对象
        if (obj instanceof Array) {
          newObj = []
        }
        for (var key in obj) {
          let val = obj[key]
          newObj[key] = typeof val === 'object' ? this.deepClone(val) : val
        }
        return newObj
      } else {
        return obj
      }
    }
  }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值