js中对象的深度复制

时间:2021-10-12 14:10:11
        // 对象的深度复制 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}