Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize Deep copy and shallow copy in JS

Shulou Source: shulou.com Published: 2022-05-31 17:48:45 10月20日 Update

This article mainly introduces "how to achieve deep copy and shallow copy of JS". In daily operation, I believe that many people have doubts about how to achieve deep copy and shallow copy of JS. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to achieve deep copy and shallow copy of JS". Next, please follow the editor to study!

Data types cannot be copied without data types. In JS, data types are divided into basic types and reference types:

Number, boolean,string,symbol,bigint,undefined,null

Reference type:

Object and some standard built-in objects Array, RegExp, String, Map, Set..

one。 Basic type data copy

The basic type data are all value types, which are stored in stack memory, and each assignment is a copy process.

Var a = 12; var b = a; II. Reference type data copy 1, shallow copy

Only one layer of data from the object is copied, and the reference type value at the deeper level will only copy the reference implementation:

Extension operators for 1.Object.assign () and ES6

Usually we use the Object.assign () method to implement a shallow copy. Object.assign () is used to assign the values of all enumerable properties from one or more source objects to the target object. It returns the target object.

Let aa = {a: undefined, func: function () {console.log (1)}, bfunction 2, c: {x: 'xxx', xx: undefined}, d: null, e: BigInt (100) F: Symbol ('s')} let bb = Object.assign ({}, aa) / / or let bb = {... aa} aa.c.x = 111Layer console.log (bb) / / Tier 1 copy Only references / / {/ a: undefined, / / func: [Function: func], / / b: 2, / c: {x: 111, xx: undefined}, / d: null, / / e: 100n, / / f: Symbol (s) / /} are copied when encountering the value of the reference type.

2.Object.create

The Object.create () method creates a new object and uses the existing object to provide the _ _ proto__ of the newly created object. Object.create (proto, [propertiesObject]) receives two parameters, one is the _ _ proto__, of the newly created object, a list of attributes

Let aa = {a: undefined, func: function () {console.log (1)}, bfunction 2, c: {x: 'xxx', xx: undefined},} let bb = Object.create (aa, Object.getOwnPropertyDescriptors (aa)) aa.c.x = 111console.log (bb) / / Tier 1 copy If you encounter the value of the reference type, you will only copy the reference / / {/ a: undefined, / / func: [Function: func], / / b: 2, / / c: {x: 111, xx: undefined}, / /} 2, deep copy

In order to avoid the impact of modifications on the data when copying an object, a deep copy must be used.

Implementation method:

1. Through JSON.stringify ()

Var a = {aJSON.stringify 1, b: 2} var b = JSON.stringify (a); an a ='a 'console.log (a, b) / / {a:' a console.log, b: 2} {"a": 1, "b": 2}

Deep copy of JSON.stringify () has its drawbacks: ignoring that value is function, undefind, symbol, and throwing a syntax error when serializing BigInt: TypeError: Do not know how to serialize a BigInt

/ / serialize function, undefind, symbol, ignore-var obj = {a:function () {}, b: undefined, c: null D: Symbol ('s'),} var objCopyed = JSON.stringify (obj) Console.log ("a:", a) / obj: {a: [Function: a], b: undefined, c: null, d: Symbol (s)} console.log ("objCopyed:" ObjCopyed) / / objCopyed: {"c": null} / / Serialization bigint throws an error-var obj = {a: 1, e: BigInt (9007199254740991)} var objCopyed = JSON.stringify (obj) / / TypeError: Do not know how to serialize a BigInt

2. Recursive implementation

Const deepCopy = (obj) = > {/ / optimize that the replicator of the value type can be placed here without one deepCopy call / / if (! obj | | typeof obj! = = 'object') throw new Error ("Please pass in non-empty objects") if (! obj | | typeof obj! = =' object') return obj let result = {} if (Object.prototype.toString.call (obj) .indexOf ('Array') > 0) { Result = []} / / another loop / / for (let key in obj) {/ / if (obj.hasOwnProperty (key)) {/ / result [key] = deepClone (objkey) / /} /} Object.keys (obj) .forEach (key = > {/ / optimize the value type replicator If you put it here, you can miss a deepCopy call / / if (obj [key] & & typeof obj [key] = 'object') {/ / result [key] = deepCopy (objkey) / /} else {/ / result [key] = obj [key] / /} result [key] = deepCopy (objkey)}) Return result} let aa = {a: undefined, func: function () {console.log (1)}, bfunc 2, c: {x: 'xxx', xx: undefined}, d: null, e: BigInt (100), f: Symbol (' s')} let bb = deepCopy (aa) aa.c.x = 123aa.func = {} console.log ("aa", aa) console.log ("bb") Bb) / / aa {/ / a: undefined,// func: {}, / b: 2 xx: undefined}, / / d: null,// e: 100n xxx', xx undefined / f: Symbol (s) / bb {/ / a: undefined,// func: [Function: func], / / b: 2 func / c: {x: 'xxx', xx: undefined} / / d: null,// e: 100n Magi Compact / f: Symbol (s) / /} so far The study on "how to achieve deep copy and shallow copy of JS" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Copy type object data learning sequence mode method property more goal error help utility next two memory parameter multiple hierarchy Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia vpn MySQL Apple OPPO Reno