Loading

关于深拷贝

  1. 利用JSON的方法,不支持函数、undefined、正则、Date、引用(环)
const b = JSON.parse(JSON.stringify(a))

2.递归
先判断参数是不是对象,是对象,在判断参数内容是不是数组,扩展运算符克隆数组,再判断函数,等于一个function,
最后如果是对象,那么递归调用deepClone,并且进行引用环处理,hash = new WeakMap()检查WeekMap中有无克隆过的对象hash.hasapi,有直接返回,没有把当前对象作为key,克隆对象作为value进行存储,hash.setapi。

        const deepClone = (a, cache) => {
            if (!cache) { cache = new Map() }
            if (a instanceof Object) {
                if (cache.get(a)) { return cache.get(a) }
                let result
                if (a instanceof Function) {
                    if (a.prototype) {
                        result = function () { return a.apply(this, arguments) }
                    } else {
                        result = (...args) => { return a.call(undefined, ...args) }
                    }
                } else if (a instanceof Array) {
                    result = []
                } else if (a instanceof Date) {
                    result = new RegExp(a.source, a.flags)
                } else {
                    result = {}
                }
                cache.set(a, result)
                for (let key in a) {
                    if (a.hasOwnProperty(key)) {
                        result[key] = deepClone(a[key], cache)
                    }
                }
                return result
            } else {
                return a
            }
        }

        const a = {
            number: 1, bool: false, str: 'hi'
        }
        const b = deepClone(a)
        console.log(b);
posted @ 2022-05-20 11:03  梧桐树211  阅读(19)  评论(0编辑  收藏  举报