js中对象的深度复制

        // 对象的深度复制 cloneObj(oldObj)
        var cloneObj = function (obj) {
            var newObj = {};
            if (obj instanceof Array) {
                newObj = [];
            }
            for (var key in obj) {
                var val = obj[key];
                newObj[key] = typeof val === 'object' ? cloneObj(val): val;
            }
            return newObj;
        };

使用方法:
var obj1 = {"a":1,"b":2};
var obj2 = cloneObj(obj1);
delete obj2.a;
console.log(obj1);// {"a":1,"b":2}
console.log(obj2); //{"b":2}

posted @ 2017-05-29 17:13  wmui  阅读(267)  评论(0编辑  收藏  举报