JS | 数组的深拷贝与浅拷贝

浅拷贝与深拷贝的区别

浅拷贝只复制指向某个对象的指针,而不复制对象本身,新旧对象还是共享同一块内存(操作新旧对象时会相互影响)。但深拷贝会另外创造一个一模一样的对象,新对象跟原对象不共享内存,修改新对象不会改到原对象。
下面总结浅拷贝和深拷贝的几种方式:

浅拷贝

Object.assign

var obj = { a: {a: "hello world", b: 31},b:34 }; 
var cloneObj = Object.assign(obj); 
cloneObj.a.a = "change world"; 
cloneObj.b = 68; 
cloneObj.a.b = 35; 
console.log(obj); 
//=> {a: {a: "change world", b: 31}b: 68} 
console.log(cloneObj); 
//=> {a: {a: "change world", b: 31}b: 68} 
console.log(obj.a === cloneObj.a); 
//=>true

lodash的 _.clone

var obj = { a: {a: "hello world", b: 31},b:34 };
var cloneObj = _.clone(obj); 
cloneObj.a.a = "change world" ; 
cloneObj.a.b = 35; 
cloneObj.b = 68 ; 
console.log(obj); 
//=>{a: {a: "change world", b: 35}b: 68} 
console.log(cloneObj);  
//=>{a: {a: "change world", b: 35}b: 68} 
console.log(obj.a === cloneObj.a);
//=>false

ES解构

var obj = { a: {a: "hello world", b: 31},b:34 }; 
var cloneObj = {...obj}; 
cloneObj.a.a = "change world"; 
cloneObj.a.b = 35; 
cloneObj.b = 68; 
console.log(obj); 
//=> {a: {a: "change world", b: 35}b: 34} 
console.log(cloneObj); 
//=> {a: {a: "change world", b: 35}b: 68} 
console.log(obj.a === cloneObj.a); 
//=>true

深拷贝

lodash的 _.cloneDeep

var obj = { a: {a: "hello world", b: 31},b:34 }; 
var cloneObj = _.cloneDeep(obj); 
cloneObj.a.a = "change world" ; 
cloneObj.a.b = 35; 
cloneObj.b = 68 ; 
console.log(obj); 
//=> {a: {a: "hello world", b: 31}b: 34} 
console.log(cloneObj); 
//=> {a: {a: "change world", b: 35}b: 68} 
console.log(obj.a === cloneObj.a); 
//=> false

JSON.parse(JSON.stringify(obj))

var obj = { a: {a: "hello world", b: 31},b:34 }; 
var cloneObj =JSON.parse(JSON.stringify(obj)); 
cloneObj.a.a = "change world" ; 
cloneObj.a.b = 35; 
cloneObj.b = 68 ; 
console.log(obj); 
//=> {a: {a: "hello world", b: 31}b: 34} 
console.log(cloneObj); 
//=> {a: {a: "change world", b: 35}b: 68} 
console.log(obj.a === cloneObj.a); 
//=> false
posted @ 2020-09-15 23:05  听说这是最长的名字了  阅读(282)  评论(0编辑  收藏  举报