手写深拷贝代码

复制代码
const obj1 = {
    age: 18,
    name: '齐晶',
    address: {
      city: 'beijing'
    },
    arr = [1, 2, 3]
}
const obj2 = deepClone(obj1)
obj2.address.city = 'chengdu'
console.log(obj1.address.city)
// 深拷贝
function deepClone(obj = {}) {
     if(typeof obj != 'object' || typeof obj ==null) {
    // 如果obj不是数组或对象 ,或者obj是null,直接返回
    return obj
    }
    // 初始化返回结果
    let result 
    if(obj instanceof Array) {
      result = []
    } else {
         result = {}
    }
    for (let key in obj) {
      // 保证key不是原型的属性
      if(obj.hasOwnProperty(key)){
        // 递归
        result[key] = deepClone([obj[key]]) 
      }
    }
  // 返回结果
  return result
}
 
复制代码

 

posted @   codejing  阅读(109)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示