JS 数组的深拷贝

  const oldObj = {
           name:"哈默",
           age:20,
           colors:['orange','green','blue'],
           friend:{
               name:"小夏"
           }
      }

    //   const newObj1 = oldObj;
    //   newObj1.name='小野';
    // console.log('oldObj',oldObj);
    // console.log('newObj1',newObj1);


    function deepClone(obj){
       
           if(typeof obj !== "object"|| obj == null){
               return obj;
           }
           let result;

           if(obj instanceof Array){
               result = [];
           }else {
               result = {}
           }

         for(let key in obj){
             if(obj.hasOwnProperty(key))
             result[key] = deepClone(obj[key])
         }



           return result

           
    }



    const newObj2 = deepClone(oldObj);
    newObj2.name = "小野";
    console.log('oldObj',oldObj);
    console.log('newObj2',newObj2);

运用循环递归 来进行数组的拷贝   
 
 




posted @ 2022-03-09 14:21  踏浪小鲨鱼  阅读(283)  评论(0)    收藏  举报