What are shallow cloning and deep cloning? Shallow cloning: directly assign the value stored in the stack to the corresponding variable. If it is a basic data type, the corresponding value is directly assigned. If it is a reference type, the address is assigned. 1. Clone the array1.1 Shallow cloningUse a for loop to do a shallow clone. var arr1 = ['demo', 1, 2]; var arr2 = []; // Shallow clone of array for (var i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } console.log(arr2); console.log(arr1 == arr2); Output:
1.2 Deep cloningUse recursion for deep cloning. function deepClone(o) { var result = []; for (var i = 0; i < o.length; i++) { result.push(deepClone(o[i])); } return result; } 2. Cloning non-array objects2.1 Shallow CloningUse a for loop to do a shallow clone. var obj1 = { a: 1, b: 2, c: 3, d: [4, 5, { e: 'demo' }] }; var obj2 = {}; // Shallow clone of object for (var i in obj1) { obj2[i] = obj1[i]; } console.log(obj2); console.log(obj1 == obj2); Output:
2.2 Deep cloningUse recursion for deep cloning. function deepClone(o) { var result = {}; for (var i in o) { result[i] = deepClone(o[i]); } return result; } 3. Integrate deep clone functionvar obj1 = { a: 1, b: 2, c: 3, d: [4, 5, { e: 'demo' }] }; var arr1 = ['demo', 1, 2]; // Deep clone function deepClone(o) { if (Array.isArray(o)) { // is an array var result = []; for (var i = 0; i < o.length; i++) { result.push(deepClone(o[i])); } } else if (typeof o == 'object') { // Not an array, but an object var result = {}; for (var i in o) { result[i] = deepClone(o[i]); } } else { // Basic type value var result = o; } return result; } console.log(deepClone(arr1)); console.log(deepClone(obj1)); This concludes this article on the detailed principles of deep and shallow cloning of JavaScript arrays and non-array objects. For more relevant JavaScript array content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed explanation of MySQL and Spring's autocommit
>>: Detailed tutorial on installing Tomcat8.5 in Centos8.2 cloud server environment
Table of contents 1. IDEA downloads the docker pl...
1. Prepare in Advance For your convenience, I cre...
Table of contents 0x0 Introduction 0x1 RBAC Imple...
This article shares the specific code of JavaScri...
In MySQL, you can use IF(), IFNULL(), NULLIF(), a...
Usage scenario: We use Alibaba Cloud and purchase...
In higher versions of Tomcat, the default mode is...
Table of contents Introduction Step 1 Step 2: Cre...
Docker version 1.13.1 Problem Process A MySQL con...
Introduction to Git Git is an open source version...
Preface The logical judgment statements we use in...
Antd+react+webpack is often the standard combinat...
Some time ago, the blogger installed the Ubuntu s...
Wired network: Ethernet Wireless network: 4G, wif...
Table of contents What is an index The difference...