Shallow copy

A shallow copy can only copy one layer, and a deeper object copy can only copy the reference path. After modifying the original variable, the value of the shallow copy will also change

var obj = {
            id:1.name:'andy'.msg: {age:18}}var o = {};
        // for(var k in obj){
        // // k is the attribute name obj[k] attribute value
        // o[k] = obj[k]
        // }
        // console.log(o);
        // o.msg = 20;


        console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --');

            Object.assign(o,obj);
            console.log(o);
            o.msg.age = 20;
            console.log(obj);

Copy the code

Deep copy

Deep copy copies multiple layers of data at each level

var obj = {
            id:1.name:'andy'.msg: {age:18}}var o= {};
      function deeCopy(newobj,olobj){
      // Iterate over old data
      for(var k in olobj){
      	// get our attribute value olobj[k] to item
		var item = olobj[k]
		// Determine the data type is
		if(item instanceof Array){
		newobj[k] = item;
		deeCopy(newobj[k],item)
}else if(item instanceof Object){
		newobj[k] = item;
		deeCopy(newobj[k],item)
}else{
		newobj[k] = item;
}		
	}
      }

        deepCopy(o,obj);
        console.log(o);

        // console.log(arr instanceof Object); // Return true to indicate that arR also belongs to object

        // o.msg.age = 20; // change the age value in MSG to 20
        // console.log(obj); // Print obj and the value inside obj is not changed


Copy the code