javascript対象または配列深度クローンに関する書き方

2826 ワード

  let obj = {
        name:"qin",
        age:123,
        arr:[1,2,34,5,{
            name:"jin",
            sex:" "
        }],
        obj1:{
            ay:[32,4]
        }
    }
    let arr1 = [2,4,2,35,2]
    function deepClone(origin,target){
        //          tostring               
        let toString = Object.prototype.toString,
            obj_array = "[object Array]";
        target = target || (toString.call(origin) == obj_array ? [] : {});//                 
        for(let prop in origin){//             
            if(origin.hasOwnProperty(prop)){//  prop     origin   
                if(typeof(origin[prop]) == "object"){//   object  
                    target[prop] = (toString.call(origin[prop]) == obj_array ? [] : {});
                    deepClone(origin[prop],target[prop]);//               
                }
                else{
                    target[prop] = origin[prop];//                   
                }
            }
        }
        
        return target;
    }
    let result = deepClone(obj);
    let result1 = deepClone(arr1);
    console.log(result,result1);