Talking about cloning JavaScript

  • 2021-12-04 09:22:50
  • OfStack

Catalogue 1, Shallow Cloning 2. Deep cloning

1. Shallow cloning

Shallow cloning cannot copy arrays and objects


var obj = {
    name : "abs",
    age : '18',
    sex : 'male'
}
var obj1 = {}
function clone(Origin,target) {
    target = target || {};// Prevent users from not entering target
    for(var k in Origin){
        target[k] = Origin[k];
    }
}
clone(obj,obj1);

2. Deep cloning

First determine what it is, the original value, array or object, and process it separately

Traversing objects Is the original value directly copy It is not the original value to judge whether it is an array or an object Is a number to form an empty array Is an object to create an empty object Once established, traverse the original object or what is in the array once Recursion

var obj = {
    name : 'lin',
    age : '18',
    sex : 'male',
    card : [1,2,3,4],
    wife : {
        name : 'bcsds',
        son : {
            name : 'aaa'
        },
        age : '23'
    }
}
var obj1 = {}
// Array of raw values and objects typeof There are differences in return values 
function deepClone(origin,target) {
    target = target || {};
    for(var k in origin) {
        if(origin.hasOwnProperty(k)){
            if(typeof(origin[k]) == 'object') {
                if(Object.prototype.toString.call(origin[k]) == '[object Array]') {
                    target[k] = [];
                }else {
                    target[k] = {};
                }
                deepClone(origin[k],target[k]);
            }else {
                target[k] = origin[k];
            }
        }
    }
}
deepClone(obj,obj1);

Related articles: