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

Principle Analysis of Javascript Deep copy

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the relevant knowledge of "the principle Analysis of Javascript Deep copy". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Why use deep copy?

In many cases, we need to assign a value to the variable and assign a value to the memory address, but when assigning a reference type, we only share a memory area, resulting in a straight line with the previous value.

Look at a specific example.

/ / assign an object var test = {a: 'asides, b:' b'} to test; / / assign test to test2 / / when test and test2 share the same memory object, that is, a shallow copy of var test2 = test; test2.a = 'a2cm; test.a = =' a2permission _ true

Illustration:

This makes it easy to understand why reference value type data interact with each other.

Realize

To implement a deep copy function, you have to say the numerical type of javascript.

Determine the type of javascript

There are the following basic types in javascript

Type description undefinedundefined type has only one value undefined, which is the value of nullnull when the variable is not assigned, and the type has only one value null, which is an empty object reference BooleanBoolean with two values true and falseString, which represents text information Number, it represents numeric information Object, it is an unordered collection of a series of attributes, including function Function and array Array.

It is impossible to judge function and array with typeof, so the Object.prototype.toString method is used here. By default, each object inherits the toString () method from Object. If the method is not overridden (obscured) by the object itself or by a method of the same name on a closer upper prototype, it returns "[object type]" when calling the object's toString () method, where the string type represents an object type.

Function type (obj) {var toString = Object.prototype.toString Var map = {'[object Boolean]': 'boolean',' [object Number]': 'number',' [object String]': 'string',' [object Function]': 'function',' [object Array]': 'array',' [object Date]': 'date',' [object RegExp]': 'regExp' '[object Undefined]': 'undefined',' [object Null]': 'null',' [object Object]': 'object'} Return map [toString.call (obj)];}

Implement deepClone

For numeric values of non-reference value types, assign values directly, while for reference value types (object), you need to traverse again and assign values recursively.

Function deepClone (data) {var t = type (data), o, I, ni; if (t = 'array') {o = [];} else if (t =' object') {o = {};} else {return data;} if (t = 'array') {for (I = 0, ni = data.length; I < ni; iTunes +) {o.push (deepClone (Data [I])) } return o;} else if (t = 'object') {for (i in data) {o [I] = deepClone (data [I]);} return o;}}

Here is a point to note that for function types, bloggers assign values directly or share a memory value. This is because the function is more to complete some functions, there is an input value and return value, and for the upper business is more to complete the business function, there is no need to really copy the function deeply.

But how do you copy the function type?

In fact, the blogger only thought of using new to operate, but function will execute it again. I can't imagine what the execution result will be! O (╯□╰) o! Others do not have any good ideas for the time being, welcome your guidance!

We have almost finished the deep copy here, but some people think that the shallow copy has not been realized.

Shallow copy?

For shallow copies, it can be understood as operating only a common area of memory! There will be danger here. Thank you. *).

If you directly manipulate the shared data without control, the data will often be abnormal and changed by other parts. Therefore, we should not directly manipulate the data source, but encapsulate some methods for the data source to CURD the data.

This is probably enough, but as a front end, you have to consider not only javascript itself, but also dom, browsers, and so on.

Element Typ

Take a look at the following code, what will the result return?

Object.prototype.toString.call (document.getElementsByTagName ('div') [0])

The answer is [object HTMLDivElement]

Sometimes the dom element is saved, and if you accidentally make a deep copy, the deep copy function above lacks the judgment of the Element element. The Element element should be judged by using instanceof. Because for different tags, tostring returns the constructor for different tags.

Function type (obj) {var toString = Object.prototype.toString Var map = {'[object Boolean]': 'boolean',' [object Number]': 'number',' [object String]': 'string',' [object Function]': 'function',' [object Array]': 'array',' [object Date]': 'date',' [object RegExp]': 'regExp' '[object Undefined]': 'undefined',' [object Null]': 'null',' [object Object]': 'object'} If (obj instanceof Element) {return 'element';} return map [toString.call (obj)];}

Another way?

JSON implementation

A deep copy can be achieved through JSON.stringify and then JSON.parse. However, data types only support basic numeric types.

Var obj = {a: 'asides, b: function () {console.log (' b')}} / / function will be filtered in JSON.stringify. JSON.stringify (obj) / / "{" a ":" a "}" principle Analysis of Javascript Deep copy "ends here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Internet Technology

Wechat

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

12
Report