JavaScript shades of copies

Shallow copy

Object.assign()

Object.assign () method can be any of a plurality of source object itself may be enumerated attribute copy to the target object, the target object and then returns. However Object.assign () shallow copy is performed, the copy attribute is a reference to an object, rather than the object itself.

const obj1 = {x: 1, y: 2};
const obj2 = Object.assign({}, obj1);

obj2.x = 2;
console.log(obj1) //{x: 1, y: 2} //原对象未改变
console.log(obj2) //{x: 2, y: 2}

const obj1 = {
    x: 1, 
    y: {
        m: 1
    }
};
const obj2 = Object.assign({}, obj1);

obj2.y.m = 2;
console.log(obj1) //{x: 1, y: {m: 2}} 原对象也被改变
console.log(obj2) //{x: 2, y: {m: 2}}

Array.concat()

const arr = [1,2,3,4,[5,6]];
const copy = arr.concat();
   
copy[0] = 2; 
arr; //[1,2,3,4,[5,6]];

// 改变数组中的引用类型值,原数组也会跟着改变
copy[4][1] = 7
arr //[1,2,3,4,[5,7]];

For the array can achieve a similar effect as well as slice () and Array.from (), etc.

Deep copy

Guess you like

Origin www.cnblogs.com/xiaobaiv/p/12667069.html