What 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.
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!

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React Strict Mode is a development tool that highlights potential issues in React applications by activating additional checks and warnings. It helps identify legacy code, unsafe lifecycles, and side effects, encouraging modern React practices.

React Fragments allow grouping children without extra DOM nodes, enhancing structure, performance, and accessibility. They support keys for efficient list rendering.

The article discusses React's reconciliation process, detailing how it efficiently updates the DOM. Key steps include triggering reconciliation, creating a Virtual DOM, using a diffing algorithm, and applying minimal DOM updates. It also covers perfo


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download
The most popular open source editor