Premise: The difference between primitive data types and object types when assigning values
JavaScript data types are divided into primitive data types and object types. The way they are stored in memory is different, resulting in differences in their assignment. Let’s take a chestnut respectively
var x = 1; var y = x; //y获得了和x同样的值 y = 2; console.log(x); // 1 var m = [1,2]; //m存放的是指向[1,2]这个数组对象的引用地址 var n = m; //n也获得 [1,2]数组对象的引用地址 n[0] = 3; console.log(m); //[3,2]
From the chestnut above, we can see that when the original data type is assigned, the actual data value is given. After the assignment, the two values are the same and will not affect each other. ; The object type gives the reference address of the original data, so the old and new data will affect each other, because it is essentially the same data object , such as the array in the above list
What is a shallow copy?
As the name suggests, shallow copy is a superficial copy method; when the attribute value is an object type, only the reference to the object data is copied, resulting in the old and new data not being completely separated. will also affect each other. Take another example...
//测试数据 var array1 = ['a',1,true,{name:'lei',age:18}]; //concat() slice() 实现浅拷贝 var array2 = array1.concat() //修改拷贝后的数据 array2[0] = 'b'; //array1[0]是原始数据类型 所以是直接赋值的 array2[3].name = 'zhang'; //array1[3]是对象数据类型 所以拷贝的是对象的引用,其实还是和原数组使用同一对象 console.log(array1); // ['a',1,true,{name:'zhang',age:18}]
In the chestnut, array2 is a shallow copy object of array1. The array elements are of primitive data types and will not affect each other (array1[0] ), but array1[3] is an object type and will still affect each other.
How to implement shallow copy
array.concat() or array.slice() in Shangli is a special implementation of shallow copy of array Way.
How to implement it yourself? Wouldn’t it be enough to traverse each attribute of the object/array and then assign it to a new object? The following implementation
//实现浅拷贝 function shallowCopy( target ){ if(typeof target !== 'object') return ; //判断目标类型,来创建返回值 var newObj = target instanceof Array ? [] : {}; for(var item in target){ //只复制元素自身的属性,不复制原型链上的 if(target.hasOwnProperty(item)){ newObj[item] = target[item] } } return newObj } //测试 var test = [1,'a',{name:'lei',age:18}]; var copy = shallowCopy(test); console.log(copy[2].name); //lei copy[2].name = 'zhang'; console.log(test[2].name); //zhang 原数据也被修改
deep copy and its implementation
From shallow copy The explanation is basically understandable. Deep copy is a 'complete' copy. After copying, the old and new data are completely separated. They no longer share the attribute values of the object type and will not affect each other.
Implementation method:
Tricky method JSON.parse(JSON.stringify(Obj))
var test = [1,'a',{name:'lei',age:18}]; var copy1 = JSON.parse(JSON.stringify(test)); //特殊方式 console.log(copy1); copy1[2].name = 'zhang' console.log(test); //[1,'a',{name:'lei',age:18}] 未受到影响
Note: This method cannot deep copy objects whose attribute values are functions. You can try it yourself
2. Implement deep copy
Having implemented shallow copy, think about it It should be that when assigning the object type attribute value, the result is not complete separation, so we need to modify the way of copying the object type attribute value, and call a deep copy on it again, thus realizing the deep copy, as follows:
//实现深拷贝 function deepCopy( target ){ if(typeof target !== 'object') return ; //判断目标类型,来创建返回值 var newObj = target instanceof Array ? [] : {}; for(var item in target){ //只复制元素自身的属性,不复制原型链上的 if(target.hasOwnProperty(item)){ newObj[item] = typeof target[item] == 'object' ? deepCopy(target[item]) : target[item] //判断属性值类型 } } return newObj } //测试 var test = [1,'a',{name:'lei',age:18}]; var copy2 = deepCopy(test); copy2[2].name = 'zhang' console.log(test); ////[1,'a',{name:'lei',age:18}] 未受到影响
Summary
Be sure to understand the reasons for shallow copy: when copying object type data, the reference address is copied, and the same data object is used; so the way to implement deep copy is to copy the object type attribute value Perform deep copy recursively to avoid direct assignment.
The above is the detailed content of How to implement deep and shallow copies of arrays and objects. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


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

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

Hot Article

Hot Tools

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

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

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.
