xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

JS Object Deep Copy & 深拷贝 & 浅拷贝

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Object.assign 是浅拷贝

针对深度拷贝,需要使用其他方法 JSON.parse(JSON.stringify(obj));,因为 Object.assign() 拷贝的是属性值。

假如源对象的属性值是一个指向对象的引用,它也只拷贝那个引用值。


function test() {
  let a = { b: {c:4} , d: { e: {f:1}} };

  let g = Object.assign({},a);

  let h = JSON.parse(JSON.stringify(a));

  console.log(g.d); // { e: { f: 1 } }
  g.d.e = 32;

  console.log('g.d.e set to 32.') 
// g.d.e set to 32.
  console.log(g); // { b: { c: 4 }, d: { e: 32 } }
  console.log(a); // { b: { c: 4 }, d: { e: 32 } }

  console.log(h); 
// { b: { c: 4 }, d: { e: { f: 1 } } }


  h.d.e = 54;
  console.log('h.d.e set to 54.') ;
// h.d.e set to 54.

  console.log(g); // { b: { c: 4 }, d: { e: 32 } }
  console.log(a); // { b: { c: 4 }, d: { e: 32 } }

  console.log(h); 
// { b: { c: 4 }, d: { e: 54 } }
}
test();

jQuery

https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript

I want to note that the .clone() method in jQuery only clones DOM elements.

https://api.jquery.com/jQuery.extend/

将两个或多个对象的内容合并到第一个对象中。

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

https://api.jquery.com/jquery.extend/

https://api.jquery.com/clone/


©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


原文地址:https://www.cnblogs.com/xgqfrms/p/6942570.html