Home > Web Front-end > JS Tutorial > body text

js realizes deep copy code sharing

小云云
Release: 2018-02-26 15:28:41
Original
2114 people have browsed it

Regarding the implementation of deep copy in js, the first thing to understand is that in order to copy complex objects, the idea of ​​​​recursion is used. The following is a step-by-step implementation and explanation through code.

function deepClone(data1,data2){
        var data2 = data2 || {}; //局部变量data2赋初值为接收的参数或者为一个空对象。
        for(var key in data1){            if(typeof data1[key] === 'object'){ //依次判断data1对象的属性是不是对象
                data2[key] =  (data1[key].constructor===Array) ? [] : {}                //判断要复制的项是对象还是数组
                deepClone(data1[key],data2[key]); //递归实现
            }else {
                data2[key] = data1[key] //如果不是的可以直接相等
            }
        }        return data2;
    }    var json = {"name":"小倪子麻麻","age": "20",arr1:[2,3,4,5]};    var json1 = {};
    json1 = deepClone (json,json1);
    json.arr1.pop();
    console.log(json); //{"name":"小倪子麻麻","age": "20",arr1:[2,3,4]};
    console.log(json1);//{"name":"小倪子麻麻","age": "20",arr1:[2,3,4,5]};
Copy after login

Related recommendations:

Detailed explanation of shallow copy and deep copy in php

Deep copy of JavaScript objects

Serialization of deep copy (deep clone) and shallow copy (shallow clone) of objects in Java

The above is the detailed content of js realizes deep copy code sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!