Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 深拷贝对象

作者:苏染瞳°   发布日期:2025-02-27   浏览:112

// 深拷贝对象的示例代码

// 方法一:使用 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 apply和call的区别

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站