Skip to content

Instantly share code, notes, and snippets.

@xgqfrms-GitHub
Created June 4, 2017 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xgqfrms-GitHub/61b92cd14761e71d9922cb182550ba11 to your computer and use it in GitHub Desktop.
Save xgqfrms-GitHub/61b92cd14761e71d9922cb182550ba11 to your computer and use it in GitHub Desktop.
JS Object Deep Copy & 深度拷贝问题

JS Object Deep Copy & 深度拷贝问题

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/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();
@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 4, 2017

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment