Js assignment after changing the existing data would modify the original data

Look at the code:

   let obj1 = {
            name: '张三',
            age: 18,
            sex: ''
        }
        let obj2 = obj1
        console.log('obj2:', obj2)
        obj2.age = 22
        console.log('obj2:', obj2)
        console.log('obj1:', obj1)

Output:

 

 solve:

Deep copying method:

 

let obj2 = JSON.parse(JSON.stringify(obj1))

 

Guess you like

Origin www.cnblogs.com/guangzhou11/p/11498166.html