js---deep copy

Shallow copy: The reference data type just assigns the reference address to another variable when assigning a value. After assignment, the two variables point to the same address in the heap memory, and any operations will affect each other.

 

Deep copy: The reference data type copies the entire content to another variable, and a new space is created in the heap memory for the copied data. The two variables actually point to two reference addresses, and subsequent operations do not affect each other.

 Three implementation ideas of deep copy:

1. Traversal + recursion (recursion is to ensure that the copy is not complete when there is nesting in the data, and the subsequent operations of the two variables affect each other)

The first step: Loop traversal (loop through each property of an object, add each property of the object and its value to another object)

Step 2: Encapsulate the function (realize the deep copy of the object, and the return value is the object after the deep copy)

Step 3: Array.isArray(): Determine whether a thing is an array

三元运算符
条件?对:不对//判断obj是否是数组类型,若是,则obj2被初始化为[],否则{}
    if (Array.isArray(obj) == true) {
        var obj2 = []
    } else {
        var obj2 = {}
    }
    var obj = { name: '李煜', age: 30, sex: true, hobby: ['打球', '听音乐'] };
    function copyObj(obj) {
        // // 判断obj2是否是数组类型
        // var obj2 = Array.isArray(obj)
        // // 如果obj2是数组类型则将obj2初始化为空数组,否则初始化为空对象
        // if (obj2){
        //     obj2=[]
        // }else{
        //     obj2={}
        // }
        var obj2 = Array.isArray(obj) ? [] : {}
        for (var key in obj) {
            // //判断属性值是否为引用类型,如果是引用类型,则需要继续循环遍历处理该属性的值(递归)
            // if (typeof obj[key] == 'object') {
            //     obj2[key] = copyObj(obj[key])
            // }else{//不是引用类型, 直接拷贝该属性的值
            //     obj2[key] = obj[key]
            // }
            obj2[key] = (typeof obj[key] == 'object' ? copyObj(obj[key]) : obj[key])

        }
        return obj2
    }
    var obj2 = copyObj(obj)
    console.log(obj, obj2);
    obj.hobby.push('coding')
    console.log(obj, obj2);

The result of running the code:

 2. JSON method

JSON.stringify () : Convert JSON object to JSON string (json string requires that each attribute name in the string must be wrapped with " ", no comments, no extra commas)

JSON.parse () : Convert a JSON string to a JSON object

var obj = { name: '李煜', age: 30, sex: true, hobby: ['打球', '听音乐'] };
var obj2=JSON.parse(JSON.stringify(obj))
console.log(obj, obj2);
obj.hobby.push('coding')
console.log(obj, obj2);

The result of running the code: 

3. assign function  (in fact, it only realizes the copy of the first-level properties of the object, and it is also a shallow copy in essence):

It is equivalent to the process of "judging whether the value of the key attribute is a reference type in obj1, and if it is, you need to continue to loop through the value of the attribute (recursively process the value of the attribute)" and this process is not executed

var obj2=Object.assign({ },obj)

var obj = { name:'李煜', age:30,sex:true,hobby:['打球','听音乐'] };
var obj2 = Object.assign( {}, obj );
console.log( obj, obj2 );   
obj.hobby.push('coding');

Guess you like

Origin blog.csdn.net/m0_53149377/article/details/127725985