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]};
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!