Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the deep and shallow copy of JavaScript

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to solve the deep and shallow copy of JavaScript". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to solve the deep and shallow copy of JavaScript".

Text

Starting with a story, yesterday, because the hospital could not prescribe medicine, I took the medicine to the drugstore to buy medicine. After entering the door, I asked the boss if he had this medicine. The boss turned into a small room and took a box of medicine. Sure enough, the name of the medicine was the same as that of milligrams, but the appearance of the box was different from that of the manufacturer. I asked the boss, "are these two medicines the same medicine? is the box different? is the composition the same?" The boss said, of course, ah, this is the same as you go to buy pork, it is also the meat of pigs, but you go to this supermarket and go to other supermarkets to buy venues. Finally, to be on the safe side, I still didn't buy the medicine.

"copy" is divided into shallow copy and deep copy. It is for the object, if it is not the object, everything is exempt. The object here can be understood as the box of medicine I took, and the shallow copy can be understood as the box of medicine taken out by the boss, although the name of the medicine is the same as mg, and then we don't know if it's really the same, maybe it may be different. Deep copy can be understood as I bought a touch of the same medicine, layer by layer of medicine name, mg, manufacturer, ingredients are all the same.

Summary:

Shallow copy is to copy the attributes of the object in turn, only one layer, not recursively to an attribute copy, which will give rise to the reference problem, that is, the memory address refers to the same address. To put it simply, it is related to the original object after the copy.

A deep copy is a recursive copy of the attributes of an object to a new object, and the memory address does not point to the same address. Simply put, it has nothing to do with the meta-object after the copy.

Let's look at an example of a shallow copy:

Let school= {'name': "W3Cschool"}; let my = {age: {count:18}, name: "W3Cschool"}; let all = {... school,...my}; my.age.count=100;console.log (all); console.log (my)

Results:

{age: {count: 100}, name: 'W3C'} {age: {count: 100}, name: 'W3C'}

The conclusion is that the properties on the object after the shallow copy is modified will modify the properties on the original object at the same time.

Let's look at another example of a deep copy:

Const _ = require ("loadsh") let my = {age: {count:18}, name: "W3Cschool"}; let all = _ .cloneDeep (my); all.age.count = 100th console.log (my); console.log (all)

Results:

{age: {count: 18}, name: 'W3C'} {age: {count: 100}, name: 'W3C'}

The conclusion is that the properties on the object after the deep copy is modified will not change the properties on the original object at the same time.

The method of copying

1. Array methods: slice and concat

Slice

Let arr = [1Jing 2 arr2 3jue 4]; let arr2 = arr.slice (0) arr2 [2] = 5scape console.log (arr); / / [1Med 2Met 3je 4] console.log (arr2); / / [1Jing 2,5,4]

The result is a deep copy when there are no objects in the array. Take a look at the following example

Let arr = [{1lux: 1 arr2 2}]; let arr2 = arr.slice (0) arr2 [2] = 5 position console.log (arr); / / [{'1conversation: 1}, {' 2conversation: 5}] console.log (arr2); / / [{'1bike: 1}, {' 2dream: 5}]

It becomes a shallow copy when there are objects in the array.

Concat

Let arr = [1Jing 2Jing 3jue 4]; let arr2 = [] .concat (arr); arr2 [2] = 5bot console.log (arr); / / [1Med 2Met 3Jing 4] ✔ console.log (arr2); / / [1Jing 2,5,4]

When there are no objects in the array, the result is a deep copy, as shown in the following example

Let arr = [{1:1}, {2:2}]; let arr2 = arr.cancat (0) arr2 [1] [2] = 5 position console.log (arr); / / [{'1percent: 1}, {' 2percent: 5}] ❌ becomes a reference to console.log (arr2); / / [{'1percent: 1}, {' 2percent: 5}]

It becomes a shallow copy when there are objects in the array.

Summary: a deep copy is made only when the array is an one-dimensional array and does not contain objects

(recommended tutorial: JavaScript tutorial)

2.Object.assgin ()

Let a = {console.log 1 console.log 2}; a.b.c=3 b = Object.assign ({}, a); let b = Object.assign ({}, a); a.av 3x console.log (a) / / {a: 3, bvv 2} let (b) / / {aRV 1L b: {CMV 2}} Console.log (a) / / {a: 1, b: {CMV 3}} console.log (b) / / {a: 1, b: {CMV 3}} ❌ becomes a reference

Summary: Object.assgin becomes a reference solution if it involves nesting multiple objects: convert it to a string first using JSON.stringify (), and then to an object through JSON.parse ()

3.JSON.parse (JSON.stringify ())

Let a = {JSON.stringify 1 W3Cschool b: {fn:function 2}}; let my b = JSON.parse (JSON.stringify (a)) a.b.croup 3 console.log (a) / / {ARAV 1D b: {age 3}} console.log (b) / / {av v 1Lever b: {CVA 2}} ✔ let school= {'name': "W3Cschool", fn:function () {}; let my = {age: {count:18}, name: "W3Cschool"} Let all=JSON.parse (JSON.stringify ({... school,...my})) console.log (all); / {'name': "W3Cschool", age: {count:18}}; / / ❌ lost fn

Summary: JSON.parse (JSON.stringify ()) this method has some limitations, will lose fn.

4. Handwritten deep copy

Let deepClone= (obj) = > {if (obj==undefined) return obj; / / undefined = = null if (obj instanceof RegExp) return new RegExp (obj); if (obj instanceof Date) return new Date (obj); if (typeof objackers = "object") return obj; let newObj = new obj.constructor; for (let key in obj) {if (obj.hasOwnProperty (key) {newObj [key] = deepClone (objkey)}} return newObj } let obj1 = {name: {age: "10"} let n = deepClone (obj1) obj1.name.age = "231" console.log (n); / {name: {age: "10"} ✔ let obj = {name: "W3Cschool"} obj.aaa=objlet n = deepClone (obj1) console.log (n); / / endless cycle ❌

To solve this problem, you can use WeakMap

Let deepClone= (obj,hash=new WeakMap ()) = > {if (obj==undefined) return obj; / / undefined = = null if (obj instanceof RegExp) return new RegExp (obj); if (obj instanceof Date) return new Date (obj); if (typeof objets = "object") return obj; if (hash.has (obj) return hash.get (obj); let newObj = new obj.constructor; hash.set (obj,newObj)) For (let key in obj) {if (obj.hasOwnProperty (key)) {newObj [key] = deepClone (obj [key], hash)}} return newObj;}

CloneDeep of 5.lodash

Source code address: https://github.com/lodash/lodash/blob/86a852fe763935bb64c12589df5391fd7d3bb14d/.internal/baseClone.js

`

Cloning method in 6.vue-router Source Code

Function clone (value) {if (Array.isArray (value)) {return value.map (clone)} else if (value & & typeof value = 'object') {const res = {} for (const key in value) {res [key] = clone (value [key])} return res} else {return value} let arr = [{1:1}, {2:2}, function () {}] Let arr2 = clone (arr) arr2 [1] [2] = 5 console.log (arr) / / [{'1copies: 1}, {' 2copies: 2}, [Function (anonymous)]] ✔ deep copy console.log (arr2) / / [{'1bike: 1}, {' 2employees: 5}, [Function (anonymous)]] function extend (a, b) {for (const key in b) {a [key] = b [key]} return a} let b = {let 1LING b: {cvav 2}}; let a = extend ({}, b); a.b.center5scape console.log (a) / / {a: 1, b: {c: 5}} console.log (b); / / {a: 1, b: {c: 5}} shallow copy Thank you for your reading, the above is the content of "how to solve the deep and shallow copy of JavaScript". After the study of this article, I believe you have a deeper understanding of how to solve the problem of deep and shallow copy of JavaScript, and the specific use needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report