5

foreword

This article analyzes the shallow copy and deep copy that are often encountered in javascript development and summarizes various implementation methods on the Internet, hoping to help everyone.

What is shallow copy and deep copy?

Let’s talk about the data types of Javascript first?

basic type:

  1. Number (Number)
  2. Character type (String)
  3. Boolean type (Boolean)
  4. Null
  5. Undefined
  6. Symbol

Reference type:

  1. Object type (Object)
  2. Array type (Array)
  3. Function type (Function)
  4. Regular Type (Regex)
  5. Date type (Date)

Shallow copy definition:

Shallow copy actually only copies the value type reference type and can also copy the past, but the copy is the pointer address of the reference type. If it is later modified, both parties will be affected, rather than the real copy, so there is the possibility of the parent object being tampered with.

Deep copy definition:
Deep copy means not only copying the value type but also copying the reference type, but the pointer addresses of the reference type are independent and cannot be affected by mutual modification.

Knowing the definitions of deep copy and shallow copy, let's talk about how to implement it?

Implement shallow copy

array:

  • […]
  • [].slice()
  • [].splice(0)
  • Array.from()

Object:

  • {...}
  • Object.assign({},a)

Works with both arrays and objects

  • clone() method in lodash package

Implement deep copy method

Works with both arrays and objects

  • JSON.parse(JSON.stringify()) Disadvantage: Cannot copy undefined and function types
  • Recursive method (traversal), disadvantage: can not solve the problem of circular reference
  • jQuery's $.extend() method
  • cloneDeep() method in npm lodash package (recommended)

Summarize

1. Understand what shallow copy and deep copy are and the difference, and then find solutions and implementation methods after understanding.

quote

Detailed explanation of shallow copy and deep copy of js object
how-do-i-deep-clone-an-object-in-react
lodash cloneDeep


Awbeci
3.1k 声望213 粉丝

Awbeci