Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the situations of deep copy of javascript?

Shulou Source: shulou.com Published: 2022-06-02 02:48:27 10月14日 Update

Most people do not understand the knowledge points of this article "what is the situation of deep copy of javascript?", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what is the situation of deep copy of javascript?"

Deep copy: the name in the reference data type exists in the stack memory and the value exists in the heap memory, but the stack memory provides a referenced address to the value in the heap memory. The deep copy is to add a pointer and apply for a new memory, so that the added pointer points to the new memory. Method 1: use Object.assign (), which is generally used for data with simple data type and no more than 1 layer, because Object.assign cannot be copied deeply.

Const strJson = {id:'12343231', name:' Zhang San', age:23, inof: {sex:' male'}, sjid:null, strHandle () {console.log ('111111111');}} obj.name =' lisi' obj.inof.sex = 'female' console.log ('obj',obj); console.log (' strJson',strJson)

Results:

Method 2: use JSON.parse and JSON.stringify, which are generally used for data with complex data types and deeply nested data, but undefined, function, RegExp and other types cannot be processed.

Const strJson = {id:'12343231', name:' Zhang San', age:23, inof: {sex:' Man'}, sjid:null, strHandle () {console.log ('111111111') }} const obj = JSON.parse (JSON.stringify (strJson)) obj.name = 'lisi' obj.inof.sex =' female 'console.log (' obj',obj); console.log ('strJson',strJson)

Results:

Third: use recursive copies to handle special cases in the code.

Function copyHandle (strJson) {let result; / / determine whether there is if (! strJson) return null; / / determine whether it is an object if (typeof strJson! = = 'object') return strJson; / / determine whether it is an array if (Array.isArray (strJson)) {result = [] For (let i of strJson) {result.push (copyHandle (I)}} / / determine whether it is RegExp else if (strJson.constructor===RegExp) {result = strJson} / / determine whether it is an object else {result = {} for (let i in strJson) {result [I] = copyHandle (strJson [I]) }} / / return result return result} above is the content of this article on "what is the situation of deep copy of javascript?" I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

Tags: Copy memory content data situation type result object that is point pointer article method deep knowledge article Zhang San processing complex special Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple MySQL Xiaomi Linux Shulou Technology