How to Deep clone in javascript

前端 未结 19 1764
-上瘾入骨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:50

    We can utilize recursion for making deepCopy. It can create copy of array, object, array of object, object with function. if you want, you can add function for other type of data structure like map etc.

    function deepClone(obj) {
             var retObj;
            _assignProps = function(obj, keyIndex, retObj) {
                   var subType = Object.prototype.toString.call(obj[keyIndex]);
                   if(subType === "[object Object]" || subType === "[object Array]") {
                        retObj[keyIndex] = deepClone(obj[keyIndex]);
                   }
                   else {
                         retObj[keyIndex] = obj[keyIndex];
                   }
            };
    
            if(Object.prototype.toString.call(obj) === "[object Object]") {
               retObj = {};
               for(key in obj) {
                   this._assignProps(obj, key, retObj);
               }
            }
            else if(Object.prototype.toString.call(obj) == "[object Array]") {
               retObj = [];
               for(var i = 0; i< obj.length; i++) {
                  this._assignProps(obj, i, retObj);
                }
            };
    
            return retObj;
        };
    

提交回复
热议问题