JavaScript 从浅入深 100 题训练计划--(3)深拷贝实现
要求:
// 拓展运算符 ...
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { ...obj1 };
obj2.a = 100; // obj1.a 不受影响
obj2.b.c = 999; // ❌ obj1.b.c 也变成 999
// Object.assign()
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = Object.assign({}, obj1);
obj2.b.c = 888; // ❌ obj1.b.c 也被修改
//数组的浅拷贝方法
const arr1 = [1, 2, { a: 10 }];
const arr2 = arr1.concat(); // 或 arr1.slice()
arr2[2].a = 999; // ❌ arr1[2].a 也被修改
深拷贝实现方式:
const obj = {
a: 1,
b: { c: 2 },
d: undefined, // ❌ 丢失
e: Symbol('test'), // ❌ 丢失
f: function() {}, // ❌ 丢失
g: new Date(), // ❌ 变成字符串
h: /test/, // ❌ 变成空对象 {}
i: NaN, // ⚠️ 变成 null
j: Infinity, // ⚠️ 变成 null
};
const deep = JSON.parse(JSON.stringify(obj));
structuredClone()(现代浏览器推荐)
// structuredClone()(现代浏览器推荐) // 原生 API,2022 年起浏览器支持 const obj = { a: 1, b: { c: 2 }, d: new Date(), e: new Set([1, 2, 3]), f: new Map([['x', 1]]), g: /test/i, }; const cloned = structuredClone(obj); // ✅ 支持:Object、Array、Date、RegExp、Map、Set、Blob、File // ❌ 不支持:function、Symbol、Error // ❌ 不支持:DOM 节点
1 const person = { 2 name: 'john', 3 age: 20, 4 hobbit: { 5 ball: 'footerball', 6 book: 'vue' 7 } 8 } 9 const deepClone = function (obj: any) { 10 if (obj === null || typeof obj !== 'object') { 11 return obj; 12 } 13 14 if (obj instanceof Date) { 15 return new Date(obj.getTime()); 16 } 17 18 if (obj instanceof Array) { 19 return obj.map(item => deepClone(item)); 20 } 21 const cloneObj = { 22 } 23 if (typeof obj === 'object') { 24 for (const key in obj) { 25 console.log(key) 26 cloneObj[key] = deepClone(obj[key]) 27 } 28 } 29 30 return cloneObj 31 } 32 33 console.log(deepClone(person), deepClone(person) === person)

浙公网安备 33010602011771号