Detailed explanation of the deep and shallow cloning principles of JavaScript arrays and non-array objects

Detailed explanation of the deep and shallow cloning principles of JavaScript arrays and non-array objects

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.
Deep cloning: Assign data to corresponding variables to generate new data that is unrelated to the source data (the data address has changed). That is, the properties of each level of the object.
In JavaScript, basic data types can be cloned using the symbol "=", and reference data types use the symbol "=" only to change the pointer of the variable, without performing a real cloning operation.

1. Clone the array

1.1 Shallow cloning

Use 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:

Array(3)0: "demo"1: 12: 2length: 3[[Prototype]]: Array(0)
false

1.2 Deep cloning

Use 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 objects

2.1 Shallow Cloning

Use 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:

{a: 1, b: 2, c: 3, d: Array(3)}
false

2.2 Deep cloning

Use 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 function

var 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:
  • Object.entries usage you don't know in JavaScript
  • js array fill() filling method
  • Detailed usage of js array forEach instance
  • Detailed discussion of several methods for deduplicating JavaScript arrays
  • Summary of JS tips for creating or filling arrays of arbitrary length
  • Detailed explanation of JavaScript array deduplication
  • js array entries() Get iteration method

<<:  Detailed explanation of MySQL and Spring's autocommit

>>:  Detailed tutorial on installing Tomcat8.5 in Centos8.2 cloud server environment

Recommend

The whole process of IDEA integrating docker to deploy springboot project

Table of contents 1. IDEA downloads the docker pl...

Detailed explanation of the difference between in and exists in MySQL

1. Prepare in Advance For your convenience, I cre...

Nest.js authorization verification method example

Table of contents 0x0 Introduction 0x1 RBAC Imple...

JavaScript timer to achieve limited time flash sale function

This article shares the specific code of JavaScri...

Detailed steps for deploying Tomcat server based on IDEA

Table of contents Introduction Step 1 Step 2: Cre...

Solution to the problem that Docker container cannot be stopped or killed

Docker version 1.13.1 Problem Process A MySQL con...

Install and use Git and GitHub on Ubuntu Linux

Introduction to Git Git is an open source version...

How to optimize logic judgment code in JavaScript

Preface The logical judgment statements we use in...

Detailed explanation of the solution for migrating antd+react projects to vite

Antd+react+webpack is often the standard combinat...

VMware Tools installation and configuration tutorial for Ubuntu

Some time ago, the blogger installed the Ubuntu s...

Introduction to network drivers for Linux devices

Wired network: Ethernet Wireless network: 4G, wif...