search
HomeWeb Front-endFront-end Q&AWhat is the difference between javascript deep copy and shallow copy

In JavaScript, a shallow copy only copies the memory address of the original data, which is equivalent to two data pointers pointing to the same address. If any one data element changes, it will affect the other; while the two data elements of the deep copy The data points to different addresses, and changes to any one element will not affect the other.

What is the difference between javascript deep copy and shallow copy

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

What is the difference between deep copy and shallow copy in javascript

Before exploring shallow copy and deep copy, let’s first understand the concepts of heap and stack

Both heap and stack It is an area divided into memory for storage. The stack is automatically allocated memory space, which is automatically released by the system; the heap is dynamically allocated memory, and its size is variable and will not be automatically released.

Let’s look at basic data types & reference data types (also known as complex data types)

1. Basic types: String, Number, Boolean, null, undefined, Symbol (new in ES6, represents a unique value); basic type values ​​occupy a fixed size in memory and are stored in stack memory.

2. Reference types: Object, Array, Date, Function, etc.; the value of the reference type is an object and is stored in the heap memory.

The concept of deep and shallow copy

Note: The difference between deep and shallow copy only applies to complex objects such as Array and Object.

1. Shallow copy: It only copies the memory address of the original data, which is equivalent to two data pointers pointing to the same address. Changes in any one of the data elements will affect the other.

2. Deep copy: The two data point to different addresses, and the data elements will not affect each other when they change.

Example study

1. Shallow copy

var arr = [0, 1, 2];
var arrB;
 
//把arr赋值给arrB
arrB = arr;
console.log("arr:", arr);
console.log("arrB:", arrB);
console.log("-----------改变arrB中数组元素的值后-----------");
arrB[0] = 5;
console.log("arr:", arr);
console.log("arrB:", arrB);

Operating results: arr array elements change with changes in arrB array elements

2. Deep copy ( Only do first-level deep copy)

Note: When using deep copy, you must clarify the requirements for deep copy, whether to deep copy only the first-level object attributes or array elements, or recursively Copy object properties and array elements at all levels?

Deep copy array

①. Direct traversal

var arr = [1, 2, 3, 4];
function copy(arr){
    var newArr = [];
    for(var i=0;i<arr.length;i++){
        newArr.push(arr[i]);
    }
    return newArr;
}
 
var arrB = copy(arr);
console.log("arrB:", arrB);
console.log("-----------改变arrB中数组元素的值后-----------");
arrB[0] = 5;
console.log("arr:", arr);
console.log("arrB:", arrB);

Running result: The change of arrB array element does not affect the value of arr array element

②.concat (): used to connect two or more arrays. This method does not modify the existing array, it simply returns a copy of the concatenated array.

var arr = [0, 1, 2];
var arrB;
 
//把arr赋值给arrB
arrB = arr.concat();
console.log("arr:", arr);
console.log("arrB:", arrB);
console.log("-----------改变arrB中数组元素的值后-----------");
arrB[0] = 5;
console.log("arr:", arr);
console.log("arrB:", arrB);

Run result: The elements of the arr array have not changed with the changes of the elements of the arrB array

③. slice(): This method returns a fragment of elements intercepted from the existing array to form a new array (the original array is not changed).

var arr = [0, 1, 2, 4, 5];
var arrB;
 
//把arr赋值给arrB
arrB = arr.slice();
console.log("arr:", arr);
console.log("arrB:", arrB);
console.log("-----------改变arrB中数组元素的值后-----------");
arrB[0] = 10;
arr[4] = 8;
console.log("arr:", arr);
console.log("arrB:", arrB);

Run result: Changes in the elements in the array will not affect each other

The above three methods are only for simple arrays where the array elements are basic data types. For first-level array elements, they are objects. Or for arrays of reference type variables such as arrays, the above methods will fail.

Related recommendations: javascript learning tutorial

The above is the detailed content of What is the difference between javascript deep copy and shallow copy. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software