js 简单的深拷贝
本题是通过@郝晨光 的文章受到的启发,学习来的,大家有兴趣可以看一下,而且我觉得这种写法非常通俗易懂,工作中也足够去使用了。
function DeepClone(target){ let result //1、先判断当前是否为对象 if(typeof target === 'object'){ //2、判断当前是否为数组,如果是,设置result为数组,并且循环递归 push赋值 if(Array.isArray(target)){ result = [] for (const key in target) { result = DeepClone(target[key]) } //3、判断当前是否为null,如果是直接赋值 }else if(target === null){ result = null //4、判断当前是否为RegExp,如果是直接赋值 }else if(target.constructor === RegExp){ result = target }else{ // 5、普通对象直接循环,递归 result = {} for (const i in target) { result[i] = DeepClone(target[i]) } } }else{ //如果不是对象类型直接赋值 result = target } return result } let obj1 = { a: { c: /a/, d: undefined, b: null }, b: function () { console.log(this.a) }, c: [ { a: 'c', b: /b/, c: undefined }, 'a', 3 ] } let obj2 = DeepClone(obj1); obj1.a.c = /b/ console.log(obj1) console.log(obj2)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通