Explain the depth and depth copy of objects in JS

Time:2020-9-16

preface

This paper is a sort of shallow copy and deep copy of the knowledge involved in the work is very important, in the interview is also a must, I hope to help my friends!
Explain the depth and depth copy of objects in JS

Why are deep and shallow copies produced?

First of all, we need to know a process

1. The object belongs to the reference type. In the future, the browser will open up a new memory space for it and assign it a hexadecimal address

2. Store the key value pairs of objects into memory space in a certain order

3. Assign the opened memory address to the variable (or event), and then the variable will find the memory space through the address, and then operate

Basic data types and reference data types

Data is divided into basic data type and reference data type

Basic data type

String、Number、Boolean、Null、Undefined、Symbol

The basic data type is the data stored directly in the stack

let str1 = '123';
str2 = str1;
str2 = '456';
console.log(str1); // '123'
console.log(str2); // '456'

Image examples:

I bought a pair of shoes before, but now I have another pair. If one pair is broken, the other will not be affected

Reference data type

Array、Object

The reference data type stores the reference of the object in the stack, and the real data is stored in memory

let arr1 =[1,2,3,4,5,6];
arr2 = arr1;
arr2.pop();
console.log(arr1);//[ 1, 2, 3, 4, 5 ]
console.log(arr2);//[ 1, 2, 3, 4, 5 ]

Image examples:

In the prairie, some sheep died of disease after eating rotten grass. The grassland is still grassland, but the grass inside is less; sheep are still sheep, but there are less sheep in the interior

The concept of deep copy and shallow copy

Light copy:

Just copy the reference of the object, not the object itself

Deep copy:

Copy all the objects referenced by the copied object

The difference between deep copy and shallow copy

Explain the depth and depth copy of objects in JS
Explain the depth and depth copy of objects in JS

~ Does the original data point to the same object The first layer of data is the basic data type The original data contains sub objects
assignment yes Change changes the data together Change will change the original data together
Light copy no Changes do not change the original data at the same time Change changes the data together
Deep copy no Changes do not change the original data at the same time Changes do not change the original data at the same time

Light copy

General cycle

const arr1 = [1, 2, ['ming', 'abc'], 5];

const shallowClone = (arr) => {
  const dst = [];
  for (let prop in arr) {
    if (arr.hasOwnProperty(prop)) {
        dst[prop] = arr[prop];
    }
  }
  return dst;
}

const arr2 = shallowClone(arr1);
arr2[2].push('wuhan');
arr2[3] = 5;

console.log(arr1);
console.log(arr2);

Operation results:
Explain the depth and depth copy of objects in JS

object.assign()

  • Object.assign The () method can copy the enumerable properties of any number of source objects to the target object, and then return the target objects
  • Object.assign () makes a shallow copy, copying a reference to the object’s properties, not the object itself
const obj1 = {
        username:'ming',
        skill:{
            play:['backetball','game'],
            rend: 'book',
        },
        girlfriends:['xiaomi','xiaohong','xiaolan'],
    };
    const obj2 = Object.assign({},obj1);
    Ob92. Username: 'mEMG'; // modify the basic type
    obj2. skill.read  ='e-mail'; // modify layer 2 basic types
    obj2. skill.play  =['footbool ']; // modify the level 2 reference type
    obj2.girlfriend = ['xiaoming'];
    console.log(obj1);
    console.log(obj2);

Operation results:
Explain the depth and depth copy of objects in JS

Array.prototype.concat()

Concat() is a built-in method for arrays, in which the user merges two or more arrays

This method does not change the existing array, but returns a new array

  const arr1 = [1,{username: 'ming',},];
  let arr2 = arr1.concat();
  arr1[0] = 2;
  arr1[1].username = 'meng';
  console.log(arr1);
  console.log(arr2);

Operation results:
Explain the depth and depth copy of objects in JS

Array.prototype.slice()

Slice () is also a built-in method for arrays, which returns a new object

Slice() does not change the original array

const arr1 = [1,{username:'ming',},];
let arr2 = arr1.slice();
arr2[0] = 2;
arr2[1].username = 'meng'
console.log(arr1);
console.log(arr2); 

Operation results:
Explain the depth and depth copy of objects in JS

Obj expansion operator

Expansion operator is a new operator in ES6

It can be used in copying arrays, objects and splicing arrays

We can also use const obj 2 = {… Obj 1} for shallow copy

//Copy array
const arr1 = [1, 2, 3];
const arr2 = [...arr1]; // like arr.slice()
arr2.push(8); 

console.log(arr1); // [ 1, 2, 3 ]
console.log(arr2); // [ 1, 2, 3, 8 ]

//Copy object
const obj1 = {
  name: 'ming',
  arr1: ['9', '7', '6'],
  obj: {
    name: 'meng',
    arr2: ['7', '8', '9'],
  },
};
const obj2 = {...obj1};// like arr.slice()
obj2.name = 'ming2';
obj2.arr1 = ['null'];
obj2.obj.name = 'meng2';
obj2.obj.arr2 = ['null'];

console.log(obj1);
console.log(obj2);

Operation results:
Explain the depth and depth copy of objects in JS

Deep copy

Manual recursion

function deepClone (sourceObj, targetObj) {
    let cloneObj = targetObj || {}
    if(!sourceObj || typeof sourceObj !== "object" || sourceObj.length === undefined){
        return sourceObj
    }
    if(sourceObj instanceof Array){
        cloneObj = sourceObj.concat()
    } else {
        for(let i in sourceObj){
            if (typeof sourceObj[i] === 'object') {
                cloneObj[i] = deepClone(sourceObj[i], {})
            } else {
                cloneObj[i] = sourceObj[i]
            }
        }
    }
    return cloneObj
}
let sourceObj = {
  a: 1,
  b: {
    a: 1
  },
  c: {
    a: 1,
    b: {
      a: 1
    }
  },
  d: function() {
    console.log('hello world')
  },
  e: [1, 2, 3]
}
let targetObj = deepClone(sourceObj, {})
targetObj.c.b.a = 9
console.log(sourceObj)
console.log(targetObj)

Operation results:
Explain the depth and depth copy of objects in JS

Json.parse(Json.Stringify())

JSON.stringify (): serializes a JS object into a JSON string

JSON.parse (): deserialize the JSON string into a JS object

const arr9 = [
    1,
    {
      username:'ming',
    },
  ];
  let arr10 = JSON.parse(JSON.stringify(arr9));
  arr10[0]=2;
  arr10[1].username='meng';
  console.log(arr9);
  console.log(arr10);

Operation results:
Explain the depth and depth copy of objects in JS

let obj = {
    name: 'ming',
    age: 20,
    friend: {
      name: 'ming1',
      age: 19
    }
  };
  let copyObj = JSON.parse(JSON.stringify(obj));
  obj.name = 'meng';
  obj.friend.name = 'meng1';
  console.log(obj);
  console.log(copyObj);

Operation results:
Explain the depth and depth copy of objects in JS

Function library lodash

Lodash as a JavaScript function library / tool library, it has a very good package of functions

var _= require('lodash');
const obj1 = [
  1,
  'Hello!',
  { name:'ming1' },
  [
    {
      name:'meng1',
    }
  ],
]
const obj2 = _.cloneDeep(obj1);
obj2[0] = 2;
obj2[1] = 'Hi!';
obj2[2].name = 'ming2'
obj2[3][0].name = 'meng2';
console.log(obj1);
console.log(obj2);

Operation results:
Explain the depth and depth copy of objects in JS

last

If this article is helpful to you, give it a compliment ❤️❤️❤️

Welcome to join us, learn the front end together and make progress together!
Explain the depth and depth copy of objects in JS
Explain the depth and depth copy of objects in JS

Recommended Today

How to make bat batch run with administrator’s permission

1. The first method Some computers are non administrator login, running the program, you need to prompt whether to run or not. The solutions are as follows: @ echo off %1 %2 ver|find “5.”>nul&&goto :Admin mshta vbscript:createobject(“shell.application”).shellexecute(“%~s0″,”goto :Admin”,””,”runas”,1)(window.close)&goto :eof :Admin //Add the above command at the beginning of your bat //Here are the commands you […]