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 realize Deep copy in JavaScript

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to achieve deep copy of JavaScript". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to achieve deep copy in JavaScript"!

What is a shallow copy?

With regard to the concept of shallow copy, I saw a saying on the Internet, directly on the code.

Var person = {name: "Jason", age: 18, car: {brand: "Ferrari", type: "430"}}; var person1 = person; / / they think this is a shallow copy

But I personally think that the above one doesn't involve copying at all, it's just a simple reference assignment. As far as I understand it, a shallow copy should be a property that does not take into account the reference type of the object, but only copies all members of the current object, as follows:

Function copy (obj) {var objCopy = {}; for (var key in obj) {objCopy [key] = obj [key];} return objCopy;} var person = {name: "Jason", age: 18, car: {brand: "Ferrari", type: "430"}}; var personCopy = copy (person)

In the above code, the person object has two basic types of properties name and age, and a reference type property car. When you use the above method to copy, the name and age attributes will be copied normally, but the car attribute will only be copied by reference, which will cause the copied objects personCopy and person to share a car object. This is called shallow copy.

What is a deep copy

Deep copy means that when copying, you need to make a complete copy of all the attributes of reference types in the current object to be copied, that is to say, there is no data shared between the copied object and the original object. Everything is your own.

How to achieve deep copy

To achieve deep copy, you need to consider the following factors:

Is the object passed in an object created using the object literal {} or generated by the constructor

If the object is created by the constructor, do you want to copy the properties on the prototype chain

If you want to copy attributes on the prototype chain, if there are multiple attributes with the same name on the prototype chain, which one should be retained?

Dealing with circular references

Third-party libraries implement deep copy jQuery's $.extend ()

We can do a deep copy through the $.extend () method. Fortunately, we can implement recursive extend in jQuery by adding a parameter. Call $.extend (true, {},...) Deep replication can be achieved, as shown in the following example:

Var x = {a: 1, b: {f: {g: 1}}, c: [1,2,3]}; var y = $.extend ({}, x), / / shallow copy z = $.extend (true, {}, x); / / deep copyy.b.f = x.b.f / / truez.b.f = = x.b.f / / false

But this $. Extend () method of jQuery has drawbacks, what are the drawbacks? Let's look at the following example:

Var objA = {}; var objB = {}; objA.b = objB;objB.a = objA;$.extend (true, {}, a); / / an exception occurs at this time / / Uncaught RangeError: Maximum call stack size exceeded (…)

That is, the $. Extend () in jQuery does not deal with circular references.

Deep copy using JSON object

Using the parse and stringify methods of the JSON global object to achieve deep replication is also a simple and ingenious method.

Function jsonClone (obj) {return JSON.parse (JSON.stringify (obj));} var clone = jsonClone ({aVl1})

However, there are some hidden pits when using this method, and the only objects it can correctly handle are Number, String, Boolean, Array, flat objects, that is, data structures that can be directly represented by json.

Build your own wheels.

Below we give a simple solution, of course, this solution is implemented with reference to the way of others. I hope it works for all of you.

Var clone = (function () {/ / this method is used to get the type of object and the return value is string type "Object RegExp Date Array..." Var classof = function (o) {if (o = null) {return "null";} if (o = undefined) {return "undefined" } / / the Object.prototype.toString here is likely to use Object.prototype.constructor.name / / here use Object.prototype.toString to generate the type string var className = Object.prototype.toString.call (o) .slice (8,-1); return className;} / / this variable is used to store saved attributes to deal with the problem of circular references var references = null; / / the way objects of different types are handled var handlers = {/ / regular expressions are handled by 'RegExp': function (reg) {var flags ='; flags + = reg.global? 'g':'; flags + = reg.multiline? 'm':'; flags + = reg.ignoreCase? 'i':'; return new RegExp (reg.source, flags);}, / / time object processing 'Date': function (date) {return new Date (+ date) }, / / the second parameter processed by the array is whether to make a shallow copy of 'Array': function (arr, shallow) {var newArr = [], I; for (I = 0; I < arr.length; icopies +) {if (shallow) {newArr [I] = arr [I] } else {/ / here we deal with circular references through the reference array if (references.indexOf (arr [I])! =-1) {continue;} var handler = handlers [classof (arr [I])] If (handler) {references.push (arr [I]); newArr [I] = handler (arr [I], false);} else {newArr [I] = arr [I] } return newArr;}, / / the second parameter for processing normal objects is whether to make a shallow copy of 'Object': function (obj, shallow) {var newObj = {}, prop, handler. For (prop in obj) {/ / the handling of attributes in the prototype is too complicated, so we will not do any processing here / / so we will only copy the attributes of the object itself, if (obj.hasOwnProperty (prop)) {if (shallow) {newObj [prop] = obj [prop] } else {/ / this is still dealing with the problem of circular references if (references.indexOf (obj [prop])! =-1) {continue;} handler = handlers [classof (obj [prop])] / / if there is no corresponding processing method, then copy if (handler) {references.push (obj[ prop]) directly; newObj [prop] = handler (obj [prop], false) } else {newObj [prop] = obj [prop];} return newObj;}} Return function (obj, shallow) {/ / first reset the variable references = [] that we use to handle circular references; / / We default to shallow = shallow = = undefined? True: false; var handler = handlers [class (obj)]; return handler? Handler (obj, shallow): obj;};} (); (function () {/ / below are some test codes var date = new Date (); var reg = / hello word/gi; var obj = {prop: 'this ia a string', arr: [1,2,3], o: {wow:' aha'}} Var refer1 = {arr: [1,2,3]}; var refer2 = {refer: refer1}; refer1.refer = refer2; var cloneDate = clone (date, false); var cloneReg = clone (reg, false); var cloneObj = clone (obj, false); alert ((date! = = cloneDate) & & (date.valueOf () = = cloneDate.valueOf () Alert ((cloneReg! = = reg) & & (reg.toString () = cloneReg.toString (); alert ((obj! = = cloneObj) & & (obj.arr! = = cloneObj.arr) & & (obj.o! = = cloneObj.o) & & (JSON.stringify (obj) = JSON.stringify (cloneObj); clone (refer2, false); alert ("I'm not dead yet!") / / Output: / / true / / I'm not dead yet!} ()). Now that you have a better understanding of "how to make a deep copy of JavaScript", you might as well do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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