This is the 18th day of my participation in Gwen Challenge

preface

Deep copy and shallow copy in the front-end project development process, the use of frequency, practicality are very high a small tool function.

There are many different ways to write it for different business scenarios.

Simple can directly write a shallow copy, complex and according to different parameters, processing methods will be different.

So let’s talk a little bit about light copy.

Front knowledge

But before we do a deep copy, don’t we have to know why we do a deep copy? Can’t you just assign a copy?

Why?

In JavaScript, there are two broad categories of data types: primitive and reference.

Basic types: Common data types such as numbers, strings, bools, etc. are basic types. These data types occupy a fixed size in memory and are stored in stack memory.

Reference types: Arrays and objects that we commonly use are reference types and are stored in the heap memory, which stores the storage address of the target.

The differences between the two types are:

The copy operation that is performed when a variable is assigned to another variable if it stores a primitive type.

If it is a reference type, the variable operates on the same array or object as the assigned variable.

Here’s an example:

var a = 1;
var b = a;
a = 2;
console.log(a);  / / 2
console.log(b);  / / 1

var arr1 = [1.2.3];
var arr2 = arr1;
arr1.push(4);
console.log(arr1);  / / [1, 2, 3, 4]
console.log(arr2);  / / [1, 2, 3, 4]
Copy the code

As you can see, the assignment of the basic type does not affect each other. And the reference type is the appearance of god.

In the real world of business development, if you need to copy a reference type of data, it is too easy to manipulate the data to affect another variable.

So, that answers the previous question, why do we write light copy.

Shallow copy

We have already talked about why we should write the copy tool function, so here is the body, first look at the shallow copy several ways;

Array: array.slice () a shallow copy of an Array

let a = [1.2.3.4]
let b = a.slice();

a.push(5);
console.log(a); // -> [1, 2, 3, 4, 5]
console.log(b); // -> [1, 2, 3, 4]
Copy the code

Array: array.concat ()

let a = [1.2.3.4]
let b = a.concat();

a.push(5);
console.log(a); // -> [1, 2, 3, 4, 5]
console.log(b); // -> [1, 2, 3, 4]
Copy the code

Object.assign() shallow copy of object.assign ()

let obj = {name: 'Corey'}
let obj2 = {};

Object.assign(obj2, obj); // The value of obj overwrites the duplicate value of obj2; If obj2 does not exist, add it.
obj.age = 18;
console.log(obj);   // {name: 'Corey', age: 18}
console.log(obj2);  // {name: 'Corey'}

/ / short
let obj2 = Object.assign({}, obj);
Copy the code

Deep copy

The shallow copy case is a bit more simple, but wouldn’t it be more powerful if functions were combined to automatically determine the data type and execute the copy in response?

There are two ways to write it.

1. Array and object mixing

Parse () parses JSON and converts json.stringify () to JSON.

Turning metadata into strings and reparsing it into actionable data makes a copy of the data without changing the metadata.

let data = [
    1.2.3
    {name: 'corey'.age: 12}]let dataCopy = JSON.parse(JSON.stringify(data));
Copy the code

2. Manually implement a deep copy

That’s too simplistic, right? Why don’t we implement one manually here? Why is there a simple, but also to toss a?

To be handsome? NoNoNo, of course not. In JS, there are many other types, such as functions, which cannot be copied directly in this way, so manual implementation is more complicated, but more flexible.

let obj = {
    name: 'name'.age: 23.info: {
        desc: 'hello'
    },
    color: ['red'.'green'.'blue']};let obj2 = {};

function deepClone(res, source){
    for(let key in source){
	let item = res[key];
        if(item instanceof Array){
            res[key] = [];
            deepClone(res[key], item)
        } else if(item instanceof Object){
            res[key] = {};
            deepClone(res[key], item);
        } else {
            res[key] = item;
        }
    }
}

deepClone(obj2, obj);
Copy the code

conclusion

Too sleepy, too sleepy, today’s end here.

I hope I can help you.

If you have any questions or want to discuss it, please leave a comment in the comments section.