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}
胖胖熊笔记,笔记已迁移