let obj = {
p1: undefined,
p2: null,
p3: new Date(),
p4: Symbol(),
p5: Boolean(false),
p6: String("p6"),
p7: Number(7),
p8: NaN,
p9: Infinity,
p10: new Map([[10, 10]]),
p11: new Set([1, 2, 3]),
p12: new RegExp("p11"),
p13: function () {
console.log("p12");
},
p14: { p: 1 },
};
let arr = [
undefined,
null,
new Date(),
Symbol(),
Boolean(false),
String("p6"),
Number(7),
NaN,
Infinity,
new Map([[10, 10]]),
new Set([1, 2, 3]),
new RegExp("p11"),
function () {
console.log("p12");
},
{ p: 1 },
];
const newArr = arr.slice();
newArr[newArr.length - 1].p = 2;
console.log(arr[newArr.length - 1]);
const newObj = Object.assign({}, obj);
newObj.p14.p = 2;
console.log(obj.p14);
console.log(JSON.parse(JSON.stringify(obj)), JSON.parse(JSON.stringify(arr)));
function deepCopy(obj, map = new WeakMap()) {
if (typeof obj !== "object" || obj === null) {
return obj;
}
if (map.has(obj)) {
return map.get(obj);
}
if (obj instanceof Date) {
return new Date(obj);
}
if (obj instanceof RegExp) {
return new RegExp(obj);
}
if (obj instanceof Set) {
const newObj = new Set();
map.set(obj, newObj);
obj.forEach((value) => newObj.add(deepCopy(value, map)));
return obj;
}
if (obj instanceof Map) {
const newObj = new Map();
map.set(obj, newObj);
obj.forEach((value, key) => newObj.set(key, deepCopy(value, map)));
return newObj;
}
if (obj instanceof Array) {
const newObj = [];
map.set(obj, newObj);
obj.forEach((vlaue, index) => {
newObj[index] = deepCopy(vlaue, map);
});
return newObj;
}
const newObj = Object.create(Object.getPrototypeOf(obj));
map.set(obj, newObj);
Reflect.ownKeys(obj).forEach((key) => (newObj[key] = deepCopy(obj[key], map)));
return newObj;
}
class CustomClass {}
const original1 = new CustomClass();
const cloned1 = deepCopy(original1);
console.log(cloned1 instanceof CustomClass);
const sym = Symbol("key");
const original2 = { [sym]: "value" };
const cloned2 = deepCopy(original2);
console.log(cloned2[sym]);
const original = {
p1: null,
p2: undefined,
array: [1, { nested: "value" }],
date: new Date(),
regex: /test/g,
set: new Set([1, 2, 3, sym]),
map: new Map([
["key", "value"],
[sym, "symbol"],
]),
fn: function () {
return "function";
},
};
const cloned = deepCopy(original);
console.log(cloned.array !== original.array);
console.log(cloned.array[1] !== original.array[1]);
console.log(cloned.date.getTime() === original.date.getTime());
console.log(cloned.regex.source === original.regex.source);
console.log(cloned.set.has(1));
console.log(cloned.set.has(sym));
console.log(cloned.map.get("key"));
console.log(cloned.map.get(sym));
console.log(cloned.fn());
console.log(cloned.p1);
console.log(cloned.p2);
const original3 = { name: "循环对象" };
original3.self = original3;
original3.child = { parent: original3 };
const cloned3 = deepCopy(original3);
original3.age = 12;
console.log(cloned3.self === cloned3);
console.log(cloned3.age);