search
HomeWeb Front-endJS TutorialJavaScript deep clone object

JavaScript deep clone object

Feb 28, 2017 pm 02:24 PM
javascript

I saw a deep clone object during my question today, and asked to program on the prototype chain

So I decided to review this knowledge point on a whim


Clone Object, this term looks fancy, but in fact it’s nothing. It’s just copying an object that is exactly the same.
Maybe some beginners are thinking, isn’t that simple? So easy

var obj1 = {name: 'payen'};var obj2 = obj1;

This is not a cloned object. obj1 and obj2 are basically the same object.
They point to the same memory address space
It's like they got the same small house
This is because the object is a reference Value (heap data)
Speaking of reference values
Reference values ​​in JavaScript are only objects
Note here that arrays are special objects and functions are also special executable objects.
In other words, they are also Object
The so-called deep cloning object means copying an identical small house
I don’t know if you can understand what I said= ̄ω ̄=
That is, the reference value of the deep cloning object needs to be copied, and the relative For shallow clone objects, just take the reference value.
It doesn’t matter if you don’t understand, you will understand after reading the code

Shallow clone object

First, let’s take a look at the shallow layer Clone the object

var house = {
    name: 'payen',
    people: {
        father: true,
        mother: true
    }
}function easyClone(obj){
    var newObj = {};    for(var prop in obj){        if(obj.hasOwnProperty(prop)){
            newObj[prop] = obj[prop];
        }
    }    return newObj;
}var newHouse = easyClone(house);

Don’t complain about me using easy. I can’t remember how to say “light” in English (I really don’t know how I passed CET-6)
There is a question about that for-in Small performance issues, interested children can read my other article
Portal o( ̄▽ ̄)d
This code is very simple and I won’t explain it more
Let’s take a look at chrome The console

looks great
Then let me do one thing now
Add someone to the new house

It seems that this "new house" is not new, don't be confused by the variable name
So, there are reference values, shallow cloning is not easy to use

Deep layer Clone object

In this case, what should we do
Since we want to get a new object, we can create a new object and copy the contents of the old object to the new object.
Also There is a question. What if there are still objects in the object?
Then continue to repeat the process of creating and adding. It is obviously a cyclic process
But there are two kinds of loops

  • iteration

  • Recursion

There is no doubt that recursion is better
In the recursive loop, when encountering conditions that satisfy the termination condition, layer by layer Return to end
Then we can search for reference values ​​layer by layer through recursion until there is no reference value
Let’s look at the code

var house = {
    name: 'payen',
    people: {
        father: true,
        mother: true,
        child: {
            age: 1
        }
    },
    money: [1000,2000,3000]
}function deepClone(original, target){
    var target = target || {};// 如果target为undefined或没传参,设置空对象
    for(var prop in original){// 遍历原对象
        if(original.hasOwnProperty(prop)){// 只拷贝对象内部,不考虑原型链
            if(typeof original[prop] === 'object'){// 引用值
                if(Object.prototype.toString.call(original[prop]) === '[object Array]'){
                    target[prop] = [];// 处理数组引用值
                }else{
                    target[prop] = {};// 处理对象引用值
                }// 可以用三目运算符
                deepClone(original[prop],target[prop]);// 递归克隆
            }else{// 基本值
                target[prop] = original[prop];
            }   
        }
    }    return target;
}var newHouse = deepClone(house);

The if-else written above is quite suitable for ternary arithmetic It's correct, but I think it's too verbose, and my obsessive-compulsive disorder said it was very uncomfortable to read.
In order to prove that it is really a deep clone, I deliberately made the original house more complicated
(We do not consider the deep cloning of functions, Troublesome and of little significance)
This time it is really a new house

I will not expand it
You can see the reference value of the new object Change, the old object has not changed
Below I also implemented the deep cloning object on the prototype chain
The principle is the same

var house = {
    name: 'payen',
    people: {
        father: true,
        mother: true,
        child: {
            age: 1
        }
    },
    money: [1000,2000,3000]
}Object.prototype.cloneTo = function(obj){
    var obj = obj || {};    
    for(var prop in this){        
    if(this.hasOwnProperty(prop)){            
    if(typeof this[prop] === 'object'){                
    if(Object.prototype.toString.call(this[prop]) === '[object Array]'){
                    obj[prop] = [];
                }else{
                    obj[prop] = {};
                }                
                this[prop].cloneTo(obj[prop]);
            }else{
                obj[prop] = this[prop];
            }
        }
    }    return obj;
}var newHouse = {};
house.cloneTo(newHouse);

The above is the content of JavaScript deep cloning object, please pay attention to more related content PHP Chinese website (www.php.cn)!


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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

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.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

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

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

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.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

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.

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

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.

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