递归方式实现深拷贝

function deepClone(target) {
    let result;
    if (typeof target === "object") {
        if (Array.isArray(target)) {
            result = [];
            for (const i in target) {
                result.push(deepClone(target[i]));
            }
        } else if (target === null) {
            result = null;
        } else if (
            target.constructor === RegExp ||
            target.constructor === Date
        ) {
            result = target;
        } else {
            result = {};
            for (const i in target) {
                result[i] = deepClone(target[i]);
            }
        }
    } else {
        result = target;
    }
    return result;
}
//   示例
let strObj = {
    name: "zhangshan",
    age: "23",
    info: {
        name: "lishi",
    },
    sayHi() {
        console.log("111");
    },
};
let copyObj = deepClone(strObj);
copyObj.info.name = "王五";
console.log(strObj);
console.log(copyObj);
posted @   Smile浅笑  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-04-09 element 单列查询
点击右上角即可分享
微信分享提示