//浅拷贝
var shallowCopy = function (obj) {
if (typeof obj !== 'object') {
return;
}
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key];
}
}
return newObj;
}
//深拷贝
var deepCopy = function (obj) {
//参数的判定
if (typeof obj !== 'object') {
return;
}
//对象类型的判别,属于array还是object,创建一个空值
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {//遍历包括原型链上的所有枚举属性
//判定是否自身属性
if (obj.hasOwnProperty(key)) {
newObj[key] = typeof obj[key] === "object" ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}
//测试
var sourceObj = {
flfp: "flfp",
flsp: {
slfp: {
tlfp: {
flfp: "flfp",
},
tlsp: [1, 2, 3, 4, 5, [6, 7, 8]],
},
slsp: "slsp",
}
}
console.log("sourceObj", sourceObj);
//浅拷贝
var shallowCopyObj = shallowCopy(sourceObj);
shallowCopyObj.flsp.slfp.tlsp[5].push(9);
console.log("shallowcopy shallowCopyObj", sourceObj.flsp.slfp.tlsp.toString());
sourceObj.flsp.slfp.tlsp[5].pop();
console.log("sourceObj", sourceObj.flsp.slfp.tlsp.toString());
//深拷贝
var deepCopyObj = deepCopy(sourceObj);
deepCopyObj.flsp.slfp.tlsp[5].push(9);
console.log("deepcopy copyObj", deepCopyObj);
console