& Array shallow copy deep copy

Continue much bb, directly on the code:

Type element containing the value false copy:

let obj = [1, 2]

let copyFake = obj
// let copyFake = [...obj]

copyFake[1] = 20
console.log(obj[1]) // 20
console.log(copyFake[1]) // 20

Containing element value type shallow copy:

let obj = [1, 2]

let copyShallow = obj.slice()
// let copyShallow = [...obj]

copyShallow[1] = 20
console.log(obj[1]) // 2
console.log(copyShallow[1]) // 20

Shallow copy type containing reference elements:

obj = the let [ 
    { 
        name: 'white. 1' , 
        Job: 'move bricks' 
    }, 
    { 
        name: 'white 2' , 
        Job: 'mixed cement' 
    } 
] 

the let copyShallow = obj.slice ()
 // the let copyShallow = [... obj] 

copyShallow [ . 1] .name = 'white' 
the console.log (obj [ . 1] .name) // white 
the console.log (copyShallow [. 1] .name) // white

Deep copy type containing reference elements:

obj = the let [ 
    { 
        name: 'white. 1' , 
        Job: 'move bricks' 
    }, 
    { 
        name: 'white 2' , 
        Job: 'mixed cement' 
    } 
] 

the let copyDeep = the JSON.parse (the JSON.stringify (obj )) 

copyDeep [ . 1] .name = 'white' 
the console.log (obj [ . 1] .name) // white 2 
the console.log (copyDeep [. 1] .name) // white

 

Guess you like

Origin www.cnblogs.com/wen233/p/11269270.html