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

What is a deep copy or a shallow copy of JavaScript

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

Share

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

This article mainly introduces what is the deep copy and shallow copy of JavaScript. It has certain reference value. Interested friends can refer to it. I hope you can learn a lot after reading this article.

1 shallow copy concept

Deep and shallow copies are only for reference data types such as Object and Array.

A shallow copy creates a new object that has an exact copy of the original object property value. If the attribute is a base type, the value of the base type is copied, and if the property is a reference type, the copy is the memory address, so if one object changes this address, it will affect the other object.

Sample code:

Let people = {/ / define a People object name: "Zhang San", age: 3, address: "China"} console.log ("original object:", people); let newPeople = people; / / make a shallow copy console.log ("New object:", newPeople) / / original object: {name: 'Zhang San', age: 3, address: 'China'} / / New object: {name: 'Zhang San', age: 3, address: 'China'} / / change the name newPeople.name = "tangerine cats don't get fat"; console.log ("original object:", people); console.log ("New object:", newPeople) / / original object: {name: 'orange cats don't eat fat', age: 3, address: 'China'} / / New object: {name: 'orange cats don't eat fat', age: 3, address: 'China'}

As you can see from the above example, when the name property of newPeople is modified, the original people also changes because the newly created object has the same memory address as the old object.

2 Deep copy concept

Deep copy is a complete copy of an object from memory, opening up a new area from the heap memory to store the new object, and modifying the new object will not affect the original object.

Sample code:

Let people = {/ / define a People object name: "Zhang San", age: 3, address: "China"} / / A deep copy of people let newPeople = JSON.parse (JSON.stringify (people)); console.log ("original object:", people); console.log ("New object:", newPeople) / / original object: {name: 'Zhang San', age: 3, address: 'China'} / / New object: {name: 'Zhang San', age: 3, address: 'China'} / / modify the adress attribute in the new object newPeople.address = "Russia"; console.log ("original object:", people); console.log ("New object:", newPeople) / / original object: {name: 'Zhang San', age: 3, address: 'China'} / / New object: {name: 'Zhang San', age: 3, address: 'Russia'}

As can be seen from the above example, after a deep copy, modifying the new object will not affect the original object.

3 implementation of shallow copy 3.1 Object.assign ()

The Object.assign () method 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. Object.assign () makes a shallow copy, copying references to the properties of the object, not the object itself.

Syntax:

Object.assign (target,... sources) / / target: target object; sources: source object.

If the attribute in the target object has the same key, the attribute is overridden by the attribute in the source object. The properties of the later source object will similarly override the properties of the previous source object.

Example:

Const target = {a: 1, b: 2}; const source = {b: 4, c: 5}; / / make a shallow copy const returnedTarget = Object.assign (target, source); console.log (target); console.log (returnedTarget); / / {a: 1, b: 4, c: 5} / / {a: 1, b: 4, c: 5} / / modify the value target.b = 10scape console.log (target); console.log (returnedTarget) / / {a: 1, b: 10, c: 5} / / {a: 1, b: 10, c: 5}

When the object object has only one layer, it is a deep copy. The sample code is as follows:

Const obj = {name: "orange cats don't eat fat"}; / / make a shallow copy of let newObj = Object.assign ({}, obj); / / modify the name attribute in the new object to Zhang San newObj.name = "Zhang San"; console.log ("original object:", obj); console.log ("New object:", newObj) / / original object: {name: 'orange cat doesn't get fat'} / / New object: {name: 'Zhang San'} 3.2 Array.prototype.concat ()

The concat () method is used to merge two or more arrays. This method does not change the existing array, but returns a new array.

Syntax:

Var new_array = old_array.concat (value1 [, value2 [,... [, valueN]) / / valueN optional, arrays and / or values will be merged into a new array. / / if all valueN parameters are omitted, concat returns a shallow copy of the existing array that called this method.

Sample code:

Let arr1 = [1,2, {name: "tangerine cats don't get fat"}]; / / shallow copy let arr2 = arr1.concat (); console.log ("original array:", arr1); console.log ("new array:", arr2) / / original array: [1, 2, {name: 'orange cats don't get fat'}] / new array: [1, 2, {name: 'orange cats don't eat fat'}] / / modify the original array arr1 [1] = "hhhhh"; console.log ("original array:", arr1); console.log ("new array:", arr2) / / original array: [1, 'hhhhh', {name:' orange cat doesn't get fat'}] / / new array: [1, 2, {name: 'orange cat doesn't get fat'}] 3.3 Array.prototype.slice ()

The slice () method returns a new array object, which is a shallow copy of the original array determined by begin and end (including begin, not end). The original array will not be changed.

Syntax:

Arr.slice ([begin [, end]]) / / begin: optionally, extract the index at the beginning (starting at 0), and extract the original array elements from that index. / / if the parameter is negative, it is extracted from the penultimate element in the original array, and slice (- 2) means to extract the penultimate element from the original array to the last element (including the last element). / / if begin is omitted, slice starts at index 0. / / if begin is out of the index range of the original array, an empty array is returned. / / end: optionally, extract the index at the end (starting at 0), and end the extraction of the original array elements at that index. Slice extracts all the elements indexed from begin to end in the original array (including begin, but not end). / / slice (1, 4) extracts all the elements in the original array from the second element to the fourth element (elements with index 1, 2, 3). / / if the parameter is negative, it indicates that the penultimate element in the original array ends the extraction. Slice (- 2) indicates that the penultimate element in the original array is extracted to the last element (excluding the last element, that is, only the penultimate element). / / if end is omitted, slice is extracted all the way to the end of the original array. / / if the end is greater than the length of the array, the slice will also be extracted to the end of the original array.

Sample code:

Let arr1 = [1,2, {name: "tangerine cats don't get fat"}]; / / shallow copy let arr2 = arr1.slice (); console.log ("original array:", arr1); console.log ("new array:", arr2) / / original array: [1, 2, {name: 'orange cats don't get fat'}] / new array: [1, 2, {name: 'orange cats don't eat fat'}] / / modify the original array arr1 [1] = "hhhhh"; console.log ("original array:", arr1); console.log ("new array:", arr2) / / original array: [1, 'hhhhh', {name:' orange cat doesn't get fat'}] / / New array: [1, 2, {name: 'orange cat doesn't get fat'}] 3.4 Direct assignment

Use the "=" assignment directly to achieve a shallow copy. The sample code is as follows:

Let obj1 = {/ / define an object obj1 name: "Zhang San", age: 34} let obj2 = obj1; / / shallow copy console.log ("obj1:", obj1); console.log ("obj2:", obj2); / / obj1: {name: 'Zhang San', age: 34} / / obj2: {name: 'Zhang San', age: 34} / / modify name attribute obj2.name in obj2 = "tangerine cats don't get fat" Console.log ("obj1:", obj1); console.log ("obj2:", obj2); / / obj1: {name: 'orange cats don't get fat', age: 34} / / obj2: {name: 'orange cats don't get fat', age: 34} 4 deep copy 4.1 JSON.parse (JSON.stringify ())

JSON is a syntax for serializing objects, arrays, numeric values, strings, Boolean values, and null. It is based on JavaScript syntax, but unlike it: JavaScript is neither JSON,JSON nor JavaScript.

The JSON object contains two methods: the parse () method for parsing JSON, and the stringify () method for converting objects / values into JSON strings, which are described below.

The JSON.parse () method is used to parse the JSON string and construct a JavaScript value or object described by the string. Provides an optional reviver function to transform (manipulate) the resulting object before returning.

Syntax:

JSON.parse (text [, reviver]) / / text: the string / / reviver to be parsed to the value of JavaScript. Optional, converter. If this parameter (function) is passed, it can be used to modify the original value generated by parsing before the parse function returns.

Example:

JSON.parse ('{}'); / / {} JSON.parse ('true'); / / trueJSON.parse (' "foo"'); / / "foo" JSON.parse ('[1,5, "false"]'); / / [1,5, "false"] JSON.parse ('null'); / / null

The JSON.stringify () method converts a JavaScript object or value to a JSON string, optionally replacing the value if you specify a replacer function, or optionally including only the attributes specified in the array if the specified replacer is an array.

Syntax:

JSON.stringify (value [, replacer [, space]]) / / value: the value to be serialized into a JSON string. / / replacer, optional. If the parameter is a function, each property of the serialized value will be converted and processed by the function during serialization; if the parameter is an array, only the property names contained in this array will be serialized into the final JSON string; if the parameter is null or not provided, all properties of the object will be serialized. / / space, optional, specifies a blank string for indentation to beautify the output (pretty-print); if the parameter is a number, it represents how many spaces it has; the upper limit is 10. If the value is less than 1, there are no spaces; if the parameter is a string (take the first 10 letters of a string when the length of the string exceeds 10 letters), the string will be used as a space; if the parameter is not provided (or null), there will be no spaces.

Example:

JSON.stringify ({}); / /'{} 'JSON.stringify (true); / /' true'JSON.stringify ("foo"); / /'"foo" 'JSON.stringify ([1, "false", false]); / /' [1, "false", false] 'JSON.stringify ({x: 5}) / /'{"x": 5}'

Deep copy of the sample code:

Let people = {/ / define a People object name: "Zhang San", age: 3, address: "China"} / / A deep copy of people let newPeople = JSON.parse (JSON.stringify (people)); console.log ("original object:", people); console.log ("New object:", newPeople) / / original object: {name: 'Zhang San', age: 3, address: 'China'} / / New object: {name: 'Zhang San', age: 3, address: 'China'} / / modify the adress attribute in the new object newPeople.address = "Russia"; console.log ("original object:", people); console.log ("New object:", newPeople) / / original object: {name: 'Zhang San', age: 3, address: 'China'} / / New object: {name: 'Zhang San', age: 3, address: 'Russia'}

Use JSON.stringify to convert the object into a JSON string, and then use JSON.parse () to parse the string into an object, so that a new object is generated and a deep copy is achieved. Although this method can make deep copies of arrays or objects, it cannot handle functions.

Let arr1 = [1,2, {name: "tangerine cats don't get fat"}, function () {}]; / / make a deep copy let arr2 = JSON.parse (JSON.stringify (arr1)); console.log ("original array:", arr1); console.log ("new array:", arr2) / / original array: [1, 2, {name: 'orange cats don't get fat'}, [Function (anonymous)] / / new array: [1, 2, {name: 'orange cats don't get fat'}, null]

As you can see from the above example, the function is not copied in arr2. This is because the JSON.stringify () method converts a JavaScript value (object or array) into a JSON string and cannot accept a function.

4.2 function library lodash

Lodash is a JavaScript library that provides several utility functions, and one of the most commonly used functions in the Lodash library is the cloneDeep () method. This method helps to clone objects deeply, as well as the limitations of the JSON.stringify () method, that is, non-serializable properties.

Sample code:

Const lodash = require ("lodash"); let people = {name: "Zhang San", age: 3, address: "China"} / / A deep copy of people let newPeople = lodash.cloneDeep (people); console.log ("original object:", people); console.log ("New object:", newPeople) / / original object: {name: 'Zhang San', age: 3, address: 'China'} / / New object: {name: 'Zhang San', age: 3, address: 'China'} / / modify the adress attribute in the new object newPeople.address = "Russia"; newPeople.name = "tangerine cats don't get fat"; console.log ("original object:", people); console.log ("New object:", newPeople) / / original object: {name: 'Zhang San', age: 3, address: 'China'} / / New object: {name: 'orange cats don't get fat', age: 3, address: 'Russia'} Thank you for reading this article carefully. I hope the article "what is a deep copy and a shallow copy of JavaScript" shared by the editor will be helpful to you. At the same time, I hope you will support me and pay attention to the industry information channel. More related knowledge is waiting for you 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