// 深拷贝对象的示例代码
// 方法一:使用 JSON.parse 和 JSON.stringify(简单但有局限性)
function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}
// 解释:这种方法适用于简单的对象和数组,但对于函数、undefined、Symbol 类型的值以及循环引用的对象无法正确处理。
// 示例:
const originalObject = {
    name: "Alice",
    age: 25,
    hobbies: ["reading", "coding"]
};
const clonedObject = deepClone(originalObject);
console.log(clonedObject); // 输出: { name: 'Alice', age: 25, hobbies: [ 'reading', 'coding' ] }
// 方法二:递归实现深拷贝(更全面)
function deepCloneRecursive(obj, hash = new WeakMap()) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
    if (hash.has(obj)) {
        return hash.get(obj);
    }
    const clonedObj = Array.isArray(obj) ? [] : {};
    hash.set(obj, clonedObj);
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            clonedObj[key] = deepCloneRecursive(obj[key], hash);
        }
    }
    return clonedObj;
}
// 解释:这种方法可以处理更复杂的情况,包括循环引用和嵌套对象。它使用 WeakMap 来避免重复拷贝同一个对象。
// 示例:
const complexObject = {
    name: "Bob",
    age: 30,
    friends: ["Charlie", "David"],
    details: {
        address: "123 Main St"
    }
};
complexObject.self = complexObject; // 创建循环引用
const clonedComplexObject = deepCloneRecursive(complexObject);
console.log(clonedComplexObject); // 输出: 循环引用的对象也被正确拷贝上一篇:js 对象深拷贝
下一篇:js 深拷贝
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站