<script>
function deepCopy (obj) { //深拷贝工具
if (typeof obj !== 'object' || obj === null) {
return obj;
} // 1 . 判断是否为有值对象
let copy; // 创建拷贝体
if (Array.isArray(obj)) { // 数组
copy = [];
for (let i = 0; i < obj.length; i++) {
copy[i] = deepCopy(obj[i]); // 递归调用存储赋值
}
} else { // 对象
copy = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = deepCopy(obj[key]);// 递归调用存储赋值
}
}
}
return copy;
}
const obj1 = {
foo: 'bar',
nested: {
a: 1,
b: 2,
c: {
d: 4,
e: 5
}
},
arr: [1, 2, 3]
};
const obj2 = deepCopy(obj1);
obj2.nested.c.d = 100000
console.log(obj1);
// {
// foo: 'bar',
// nested: {
// a: 1,
// b: 2,
// c: {
// d: 4,
// e: 5
// }
// },
// arr: [1, 2, 3]
// };
console.log(obj2);
// {
// foo: 'bar',
// nested: {
// a: 1,
// b: 2,
// c: {
// d: 100000,
// e: 5
// }
// },
// arr: [1, 2, 3]
// };
</script>
封装深拷贝工具
最新推荐文章于 2024-05-24 13:39:19 发布