How to Deep clone in javascript

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

    This is the deep cloning method I use, I think it Great, hope you make suggestions

    function deepClone (obj) {
        var _out = new obj.constructor;
    
        var getType = function (n) {
            return Object.prototype.toString.call(n).slice(8, -1);
        }
    
        for (var _key in obj) {
            if (obj.hasOwnProperty(_key)) {
                _out[_key] = getType(obj[_key]) === 'Object' || getType(obj[_key]) === 'Array' ? deepClone(obj[_key]) : obj[_key];
            }
        }
        return _out;
    }
    

提交回复
热议问题