手写深拷贝(JS)

手写深拷贝(JS)

代码

const oldObj = {
    name: "Jujuxiaer",
    age: 20,
    colors: ['orange', 'red', 'blue'],
    friends: {
        name: "小可"
    }
}

const newObj1 = oldObj;
newObj1.name = "小华";
console.log(oldObj);
console.log(newObj1);


function deepClone(obj = {}) {
    let ret;
    if (typeof obj !== 'object' || obj == null) {
        return obj;
    }
    if (obj instanceof Array) {
        ret = [];
    } else {
        ret = {};
    }
    for (let objKey in obj) {
        // 只拷贝对象自身的属性
        if (obj.hasOwnProperty(objKey)) {
            // 重点:递归的深拷贝,目的是为了对象的对象的值也是深拷贝
            ret[objKey] = deepClone(obj[objKey]);
        }
    }
    return ret;
}

const oldObj2 = {
    name: "Jujuxiaer",
    age: 20,
    colors: ['orange', 'red', 'blue'],
    friends: {
        name: "小可"
    }
}

const newObj2 = deepClone(oldObj2);
newObj2.name = "小华";
newObj2.colors[0] = 'black';
newObj2.age = 30;
newObj2.friends.name = "小明";
console.log('=========');
console.log(oldObj2);
console.log(newObj2);

结果:

在这里插入图片描述

代码地址:https://github.com/Jujuxiaer/front-basic-example/blob/master/%E5%93%88%E9%BB%98%E8%81%8A%E5%89%8D%E7%AB%AF/%E6%89%8B%E5%86%99%E6%B7%B1%E6%8B%B7%E8%B4%9D/index.js

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值