How to implement shallow copy

Shallow copy: Create a new object that has an exact copy of the original object's property values. If the attribute is a basic type, the value of the basic type is copied; if the attribute is a reference type, the memory address is copied. This memory address points to the same heap memory. If one of the objects changes this address, it will affect the other object.

Deep copy: Create a new object. If the attribute is a basic type, the value of the basic type is copied; if the attribute is a reference type, a new area is opened from the heap memory to store the heap pointed to by the reference type. The value in memory, modifying the value of the new object will not affect the original object.
 

1.Object.assign

const obj = {};
const source = {
  name: 'nordon',
  info: {
    age: 18
  }
};
 
Object.assign(obj, source);
console.log(obj); // {name: 'nordon', info: {…}}
复制代码

Object.assign is a method of Object. This method can be used for many purposes such as merging JS objects. One of the uses is to perform shallow copying. The first parameter of this method is the target object to be copied, and the following parameters are the source objects to be copied (it can also be multiple sources).

important point:

  • It does not copy the object's inherited properties;
  • It does not copy the non-enumerable properties of the object;
  • Properties of type Symbol can be copied.

2.Extension operator

3.Array.prototype.concat implements shallow copy

const arr = [1, 2, {name: 'nordon'}];
const newArr = arr.concat();
newArr[2].name = 'wy';
console.log(arr); 
console.log(newArr);
复制代码

4.Array.prototype.slice

const arr = [1, 2, {name: 'nordon'}];
const newArr = arr.slice();
newArr[2].name = 'wy';
复制代码

5. Traversal based on for in

6.loadsh的clone

Use recursive functions

function deepClone1(obj) {
      //判断拷贝的要进行深拷贝的是数组还是对象,是数组的话进行数组拷贝,对象的话进行对象拷贝
      var objClone = Array.isArray(obj) ? [] : {};
      //进行深拷贝的不能为空,并且是对象或者是
      if (obj && typeof obj === "object") {
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] && typeof obj[key] === "object") {
              objClone[key] = deepClone1(obj[key]);
            } else {
              objClone[key] = obj[key];
            }
          }
        }
      }
      return objClone;
    }
————————————————
版权声明:本文为CSDN博主「妖刀村雨」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_45273903/article/details/122625920

Guess you like

Origin blog.csdn.net/qq_69892545/article/details/128805781