How to Deep clone in javascript

前端 未结 19 1561
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:06

How do you deep clone a JavaScript object?

I know there are various functions based on frameworks like JSON.parse(JSON.stringify(o)) and $.extend(t

19条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 02:43

    The below function is most efficient way to deep clone javascript objects.

    function deepCopy(obj){
        if (!obj || typeof obj !== "object") return obj;
    
        var retObj = {};
    
        for (var attr in obj){
            var type = obj[attr];
    
            switch(true){
                case (type instanceof Date):
                    var _d = new Date();
                    _d.setDate(type.getDate())
                    retObj[attr]= _d;
                    break;
    
                case (type instanceof Function):
                    retObj[attr]= obj[attr];
                    break;
    
                case (type instanceof Array):
                    var _a =[];
                    for (var e of type){
                        //_a.push(e);
                        _a.push(deepCopy(e));
                    }
                    retObj[attr]= _a;
                    break;
    
                case (type instanceof Object):
                    var _o ={};
                    for (var e in type){
                        //_o[e] = type[e];
                        _o[e] = deepCopy(type[e]);
                    }
                    retObj[attr]= _o;
                    break;
    
                default:
                    retObj[attr]= obj[attr];
            }
        }
        return retObj;
    }
    
    var obj = {
        string: 'test',
        array: ['1'],
        date: new Date(),
        object:{c: 2, d:{e: 3}},
        function: function(){
            return this.date;
        }
    };
    
    var copyObj = deepCopy(obj);
    
    console.log('object comparison', copyObj === obj); //false
    console.log('string check', copyObj.string === obj.string); //true
    console.log('array check', copyObj.array === obj.array); //false
    console.log('date check', copyObj2.date === obj.date); //false
    console.log('object check', copyObj.object === obj.object); //false
    console.log('function check', copyObj.function() === obj.function()); //true
    

提交回复
热议问题