4 ways to implement deep copy in Js

concept

Deep copy: re-open a storage space in the heap memory, completely clone an identical object;
shallow copy: do not re-open up space in the heap memory, only copy the reference address in the stack memory.
In essence, the two objects (arrays) still point to the same storage space. Insert the code slice here

1. Recursive method (recommended, the safest and most commonly used in the project)

//使用递归的方式实现数组、对象的深拷贝
export function deepClone (obj) {
    
    
    let objClone = Array.isArray(obj) ? [] : {
    
    };
    if (obj && typeof obj === "object") {
    
    
        for (var key in obj) {
    
    
            if (obj.hasOwnProperty(key)) {
    
    
                //判断ojb子元素是否为对象,如果是,递归复制
                if (obj[key] && typeof obj[key] === "object") {
    
    
                    objClone[key] = deepClone(obj[key]);
                } else {
    
    
                    //如果不是,简单复制
                    objClone[key] = obj[key];
                }
            }
        }
    }
    return objClone;
};   

2. JSON.stringify(); (this is not recommended, there are pitfalls)

Ordinary objects can also be deep copied, but! ! ! When the object content item is number, string.boolean, there is no problem. However, if the object content item is undefined, null, Date, RegExp, function, error. Copying with JSON.parse(JSON.stringify()) will cause problems.

3. Use the cloneDeep() method in the third-party library lodash

Whether it is recommended to use depends on the situation. If we only need a deep copy function in our project, it is not worth introducing the entire third-party library for a function in this case. It is better to write a recursive function for the project
. In fact, the bottom layer of the lodash.cloneDeep() method is a recursive method. It just encapsulates a layer of cloneDeep's main function baseClone in the outer layer.
Therefore, if the lodash library was not used in the original project, there is no need to introduce it for this function.

4. The extend() method of jquery performs deep copy (recommended to be used in JQ)

This method is only available for projects built with JQuery. The extend carried by JQuery itself

let obj = {
    
     a: {
    
     c: 2, d: [1, 3, 5], e: "哇哇哇" }, b: 4 };
let newObj = $.extend(true, {
    
    }, obj1);
 //拷贝完成obj.b = 20;console.log(newObj.b); //输出 4

Summarize:

How to make a deep copy:

Recursive functions (recommended, more used in projects, smaller, safer)

JSON.stringify() and JSON.parse() ; (not recommended, if you encounter variables of type Function, Date, etc., it is easy to have some unexpected problems)

The cloneDeep() method of the third-party library lodash

JQuery's extend() function (recommended to be used in JQuery projects, other projects are still recommended to use recursive functions)

Guess you like

Origin blog.csdn.net/weixin_49295874/article/details/130635106