js deep copy and shallow copy

I haven't delved into this issue before, and I haven't paid much attention to it... Maybe I haven't encountered it or I haven't figured out what's going on, and then I check in the major communities to find out, it's probably the case :

Except for objects, other copies are copies of values, and objects are special. When js stores objects, it stores the address pool, so when we copy an object, the newly copied object and the original object use The same address pool, that is to say, when you change the value of the newly copied object, the value of the original object will also be changed, but in many cases, we do not want to modify the value of the original object. In this case, a deep copy is required. . A deep copy is to create a new world without affecting the original object.

Shallow copy example:

Deep copy implementation:

One: use json parsing to achieve

var test = {
 name:
    {
        xing:{ first: 'Li', second:'King' }, ming:'Old man' },
        age :40,
        friend :[ 'Pharaoh next door', 'Mr. Zhang', 'Mr. Li' ]
    }
var result = JSON.parse(JSON.stringify(test)) ;
result.age = 30;
result.name.xing.first = '宋' ;
result.friend.push( 'Fan Bingbing' );
console.log(test) ;
console.log(result)  ;         

two.

function deepClone(obj) {
     var newObj = obj instanceof Array ? [] : {};
     // obj is a basic data type, return obj directly 
    if ( typeof obj !== 'object' ) {
         return obj;
    } else {
     // obj belongs to array or object, iterate over them 
        for ( var i in obj) {
            newObj[i] = typeof obj[i] === 'object' ? deepClone(obj[i]):obj[i]; 
        }
    }
    return newObj;
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324457278&siteId=291194637