javascript深拷贝,看这篇就够了

158 阅读2分钟

在JavaScript中,深拷贝对象是一个常见的需求,尤其是在处理复杂数据结构时。深拷贝会创建一个全新的对象,并递归地复制原对象的所有属性及其嵌套的对象。以下是一些实现深拷贝的方法:

1. 使用 JSON.parseJSON.stringify

这是最简单的方法,适用于大多数情况,但有一些限制,例如不能处理函数、循环引用和某些特殊对象(如 DateRegExp 等)。

function deepCopy(obj) {
    return JSON.parse(JSON.stringify(obj));
}

const originalObj = {
    name: 'Alice',
    age: 25,
    address: {
        city: 'New York',
        zip: '10001'
    }
};

const copiedObj = deepCopy(originalObj);
console.log(copiedObj); // { name: 'Alice', age: 25, address: { city: 'New York', zip: '10001' } }

2. 使用递归函数

这种方法可以处理更复杂的对象,包括函数、循环引用和其他特殊对象。

function deepCopy(obj, hash = new WeakMap()) {
    if (obj instanceof RegExp) return new RegExp(obj);
    if (obj instanceof Date) return new Date(obj);
    if (obj === null || typeof obj !== 'object') return obj;

    if (hash.has(obj)) return hash.get(obj);

    let target = Array.isArray(obj) ? [] : {};
    hash.set(obj, target);

    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            target[key] = deepCopy(obj[key], hash);
        }
    }

    return target;
}

const originalObj = {
    name: 'Alice',
    age: 25,
    address: {
        city: 'New York',
        zip: '10001'
    },
    hobbies: ['reading', 'coding'],
    getAge: function() {
        return this.age;
    }
};

const copiedObj = deepCopy(originalObj);
console.log(copiedObj); // { name: 'Alice', age: 25, address: { city: 'New York', zip: '10001' }, hobbies: [ 'reading', 'coding' ], getAge: [Function: getAge] }

3. 使用第三方库

一些流行的第三方库如 lodash 提供了深拷贝的功能,使用起来非常方便。

使用 lodash

首先安装 lodash

npm install lodash

然后在代码中使用 _.cloneDeep 方法:

const _ = require('lodash');

const originalObj = {
    name: 'Alice',
    age: 25,
    address: {
        city: 'New York',
        zip: '10001'
    },
    hobbies: ['reading', 'coding'],
    getAge: function() {
        return this.age;
    }
};

const copiedObj = _.cloneDeep(originalObj);
console.log(copiedObj); // { name: 'Alice', age: 25, address: { city: 'New York', zip: '10001' }, hobbies: [ 'reading', 'coding' ], getAge: [Function: getAge] }

总结

  • JSON.parseJSON.stringify:简单易用,但有局限性。
  • 递归函数:灵活且功能强大,可以处理各种复杂对象。
  • 第三方库:如 lodash,提供了丰富的功能和更好的性能。

希望这些方法能帮助你实现深拷贝对象。如果有任何疑问或需要进一步的解释,请随时提问。 PS:学会了记得,点赞,评论,收藏,分享