Deep copy is a copy that copies the parent object to the child object, and the memory and subsequent operations of the two do not affect each other. This article mainly shares with you the discussion of js deep copy examples, hoping to help everyone.
(1) Method 1
function copy(obj1,obj2){ var obj2=obj2||{}; for(var name in obj1){ if(typeof obj1[name] === "object"){ //先判断一下obj[name]是不是一个对象 obj2[name]= (obj1[name].constructor===Array)?[]:{}; copy(obj1[name],obj2[name]); //然后来无限递归 }else{ obj2[name]=obj1[name]; //如果不是对象,直接赋值。 } } return obj2; }
Usage method:
var obj1 = { se:[{a:1,b:2},{c:3}], sa:{a:"g"}, sc:function(){console.log(1)} }var n_obj = copy(obj1,{}) console.log(n_obj)
(2) Method 2
function d_clone(obj) { return Object.getPrototypeOf(Object.create(obj)); }
Usage method:
var obj1 = { se:[{a:1,b:2},{c:3}], sa:{a:"g"}, sc:function(){console.log(1)} }var n2_obj = d_clone(obj1); console.log(n2_obj)
(3) Method 3
JSON.parse(JSON.stringify(obj)
Description: The attributes of obj cannot contain functions.
(1) Method 1
function copy(obj1,obj2){ var obj2=obj2||{}; for(var name in obj1){ if(typeof obj1[name] === "object"){ //先判断一下obj[name]是不是一个对象 obj2[name]= (obj1[name].constructor===Array)?[]:{}; copy(obj1[name],obj2[name]); //然后来无限递归 }else{ obj2[name]=obj1[name]; //如果不是对象,直接赋值。 } } return obj2; }
Usage method:
var obj1 = { se:[{a:1,b:2},{c:3}], sa:{a:"g"}, sc:function(){console.log(1)} }var n_obj = copy(obj1,{}) console.log(n_obj)
(2) Method 2
function d_clone(obj) { return Object.getPrototypeOf(Object.create(obj)); }
Usage method:
var obj1 = { se:[{a:1,b:2},{c:3}], sa:{a:"g"}, sc:function(){console.log(1)} }var n2_obj = d_clone(obj1); console.log(n2_obj)
(3) Method 3
JSON.parse(JSON.stringify(obj)
Description: The attributes of obj cannot contain functions.
Related recommendations:
Related recommendations:
In-depth understanding of JavaScript deep copy performance
What is js deep copy And shallow copy and its implementation
The difference between JavaScript shallow copy and deep copy
The above is the detailed content of Discussion on js deep copy examples. For more information, please follow other related articles on the PHP Chinese website!