search
HomeWeb Front-endJS TutorialCode examples of shallow cloning and deep cloning of JS objects

This article brings you code examples about shallow cloning and deep cloning of JS objects. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Shallow Clone

Look at the code first:

/**
 * 浅克隆 克隆传入对象,只克隆一层
 * @param {any} source
 */
function shallowClone(source) {
    var tiaget = createEctype(source);  //创建一个副本
    // 将原对象的所有属性值赋值到新对象上
    for (var property in source) {
        if (source.hasOwnProperty(property)) {
            tiaget[property] = source[property];
        }
    }
    /**
    * 创建副本
    * @param {any} source
    */
    function createEctype(source) {
        var newObject = {};
        if (Array.isArray(source))
            newObject = [];
        return newObject;
    }

    return tiaget;
}

Execute the test:

var a={a1:1,a2:2,a3:[1,2,3]};
 var b={b1:1,b2:2,b3:[4,5,6]}
 a.b=b;
 b.a=a;
 a.a4=[a,b];
 b.b4=[a,b];
 a.fn=function(){console.log(this.b);};
 
 var newa=shallowClone(a);

The test code defines a self-referential object

a===a.a4[0];    // true
a===a.b.a;    // true

Execute the shallowClone method to obtain a copy of object a newa

a === newa;              // false
newa ===  newa.a4[0];    // false
newa ===   newa.b.a;     // false
a === newa.a4[0];        // true
a === newa.b.a;          // true

Test execution speed:

/**
获取传入方法在规定时间内执行次数

示例:
var test = function(){

};
runTime(test,1)
表示test方法 在1秒中执行了6819005次
**/

/**
 * 获取传入方法在规定时间内执行次数
 * @param {any} fn 执行的方法
 * @param {any} time 规定的时间,单位为秒
 */
function runTime(fn, time) {
    var startTime = Date.now();
    var count = 0;
    while (Date.now() - startTime < time * 1000) {
        fn.call();
        count++;
    }
    return count;
}

Code examples of shallow cloning and deep cloning of JS objects

Deep Clone

Code:

/**
 * 深克隆
 * 
 * 示例:
 * var a={a1:1,a2:2,a3:[1,2,3]};
 * var b={b1:1,b2:2,b3:[4,5,6]}
 * a.b=b;
 * b.a=a;
 * a.a4=[a,b];
 * b.b4=[a,b];
 * a.fn=function(){console.log(this.b);return this.b;};
 * 
 * var newa=deepClone(a);
 * newa.a1=123;
 * newa.fn();
 */
function deepClone(source) {
    this.objKeyCache = [];      // 对象缓存
    this.objValueCache = [];    // 对象克隆缓存

    this.clone = function (source) {
        var target = createEctype.call(this, source);
        for (var property in source) {
            if (source.hasOwnProperty(property)) {
                var value = source[property];
                if (typeof value === "number"
                    || typeof value === "boolean"
                    || typeof value === "symbol"
                    || typeof value === "string"
                    || typeof value === "function"
                    || typeof value === "undefined"
                    || value === null)
                    target[property] = value;
                else if (typeof value === "object") {
                    // 如果源对象在对象缓存中存在,就用对象克隆缓存中的值赋值
                    var index = this.objKeyCache.indexOf(value);
                    if (index >= 0)
                        target[property] = this.objValueCache[index];   
                    else {
                        target[property] = this.clone( value);
                    }
                }
                else
                    throw "未知数据类型" + (typeof value);
            }
        }

        return target;
    };
    /**
     * 创建副本
     * @param {any} source
     */
    function createEctype(source) {
        var target = {};
        if (Array.isArray(source))
            target = [];
        this.objKeyCache.push(source);
        this.objValueCache.push(target);
        return target;
    }
    var newObject = this.clone(source);
    // 释放缓存,防止内存溢出
    this.objKeyCache = [];
    this.objValueCache = [];
    return newObject;
}

Execution test:

var a={a1:1,a2:2,a3:[1,2,3]};
var b={b1:1,b2:2,b3:[4,5,6]}
a.b=b;
b.a=a;
a.a4=[a,b];
b.b4=[a,b];
a.fn=function(){console.log(this.b);return this.b;};

var newa=deepClone(a);
a === newa;            // false
newa === newa.a4[0]    // true
newa === newa.b.a;     // true
a === newa.a4[0];      // false
a === newa.b.a;        // false

Code examples of shallow cloning and deep cloning of JS objects

##Test execution speed:

Code examples of shallow cloning and deep cloning of JS objects

The above is the detailed content of Code examples of shallow cloning and deep cloning of JS objects. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

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.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

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 Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

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

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

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.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

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 Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

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.