function deepClone(obj) {
if (typeof obj != 'object' || obj == null) {
return obj;
}
let result;
if (obj instanceof Array) {
result = [];
} else {
result = {};
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const element = obj[key];
result[key] = deepClone(element);
}
}
return result;
}
let obj = {
name: "伍子胥",
girl: {
name: 'any',
items: [1, 2, 3]
}
};
let obj2 = deepClone(obj);
obj2.girl.name = 'abc';
obj2.girl.items[0] = 999;
console.log(obj.girl.name);
console.log(obj.girl.items[0]);
网友评论