JS手写深拷贝

方法一:

使用JSON序列化后再反序列化

优点:

  1. 编码简洁

缺点:

  1. 由于 json 只支持 string、number、Boolean、null、object、Array,所以该方法不支持 Date、undefined、函数、正则等数据
  2. 不支持引用(即环状结构)
const b = JSON.parse(JSON.stringify(a))
方法二:

使用递归实现深拷贝(不考虑跨 iframe)

要点:
1.递归
2.判断类型
3.检查环
4.不拷贝原型上的属性

const deepClone = (a, cache) => {
    if (!cache) {
        cache = new Map() // 临时创建并递归传递缓存
    }
    if (a instanceof Object) { // 不考虑跨 iframe
        if (cache.get(a)) { return cache.get(a) }
        let result
        if (a instanceof Function) {
            if (a.prototype) { // 有 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 Date(a - 0)
        } else if (a instanceof RegExp) {
            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', empty1: undefined, empty2: null,
    array: [
        { name: 'frank', age: 18 },
        { name: 'jacky', age: 19 }
    ],
    date: new Date(2000, 0, 1, 20, 30, 0),
    regex: /\.(j|t)sx/i,
    obj: { name: 'frank', age: 18 },
    f1: (a, b) => a + b,
    f2: function (a, b) { return a + b }
}
a.self = a
const b = deepClone(a)
b.self === b // true
b.self = 'hi'
a.self !== 'hi' //true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值