1. Introduction

Deep and shallow copies are often used in interviews to gauge your understanding of basic types and reference types.

Speaking of shallow copy, memory and data types have to be mentioned here.

In JS, data types are divided into basic data types and reference types. Basic data types (String, Number, Boolean, undefined, NULL, symnol……) , reference type Object (Array, Object, Function……) . Memory is divided into stack memory and heap memory, where stack memory is used for storageBasic data types(fast access, small storage) andAddress of the reference type(Access is slow, storage is large, and reference Pointers are stored on the stack and point to the reference itself), while heap memory stores reference data types.

2. Assignment

Assignment is the process of assigning a value or object to a variable

2.1 Basic data type: Assignment. After assignment, the two variables do not affect each other
2.2 Reference Data Types: Address assignment. Two variables have the same reference to the same object and affect each other
<script> // Basic type var a = 100; var b = a; a = 200; console.log(a, b); Var a = {c: 1000}; var a = {c: 1000}; var b = a; a.c = 2000; console.log(a.c, b.c); // 2000, 2000 all 2000, a b point to the same data </script>Copy the code

Shallow and deep copies are often used when you don’t want to change variable A to affect variable B during development.

3. The shallow copy

3.1 Create a new object that has an exact copy of the original object property values. If the property is a primitive type, it copies the value of the primitive type, and if the property is a reference type, it copies the memory address, so if one object changes the address, it affects the other object.

<script> function cloneShallow(source) { var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } return target; } var a1 = { b: { c: {} } }; var a2 = cloneShallow(a1); // shallow copy a2.b.c = {d: "1"}; console.log("a1---", a1); console.log("a2---", a2); Var a5 = {b: {d: [1,2]}}; var a6 = cloneShallow(a5); A6.b.d = [3,4]; console.log("a5---", a5); console.log("a6---", a6); Var a3 = {b:'9'}; var a3 = {b:'9'}; var a4 = cloneShallow(a3); a4.b = '10'; console.log("a3---", a3); console.log("a4---", a4); </script>Copy the code

3.2 the Object. The assign ()

The object.assign () method copies the enumerable properties of any number of source objects to the target Object and returns the target Object. Note that Object.assgin() makes a shallow copy, copying references to the attributes of the Object, not the Object itself.

Object.assign(target, ... sources)

3.3 Array. The prototype. The concat ()

3.4 Array. The prototype. The slice ()

3.5… Obj expansion operator

The expansion operator is a new addition to ES6.

4. A deep copy

4.1 Deep Copy Copies all attributes and dynamically allocated memory that the attributes point to. Deep copy occurs when an object is copied along with the object it references. Deep copy is slower and more expensive than shallow copy. The two objects do not affect each other

<script> function isObject(obj) { return typeof obj === "object" && obj ! = null; } function cloneDeep(source) { if (! isObject(source)) return source; Var target = array. isArray(source)? [] : {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (isObject(source[key])) { target[key] = cloneDeep(source[key]); } else {target[key] = source[key]; } } } return target; } var obj = { title: "study", list: ["1", "2", "3"], }; var obj2 = cloneDeep(obj); obj2.title = "play"; obj2.list = ["3", "4"]; console.log("obj", obj); console.log("obj2", obj2); </script>Copy the code

4.2 JSON. Parse (JSON. Stringify (object))

Json.stringify () : Converts an object into a JSON string.
Json.parse () : Parses strings into objects.
Parse (json.stringify ()) serializes JavaScript objects (converting them to JSON strings) and returns them to JavaScript objects. As soon as we do that, we create a new object and the object opens up a new stack. To achieve deep copy.
Pay attention to
Note the limitations of this method:
1, cannot store function or Undefined, otherwise it will lose function or Undefined;
2, do not store the time object, otherwise it will become a string;
3. Do not store RegExp or Error objects, otherwise they will become empty objects.
4, can not store NaN, Infinity, -infinity, otherwise will be null;
5,… To be specific, there are differences between JavaScript and JSON, and the two incompatible will cause problems.

4.3 Function library Lodash

CloneDeep () methodCopy the code
npm i --save lodash
var _ = require('lodash');

var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

Copy the code

5. To summarize

I learned the difference between deep copy and shallow copy through learning and sorting, and copied data better according to the scene when writing business code. Of course, there are some logic incompleteness in the article, welcome to correct.

6 reference

Wood and poplar front end advanced