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();
jQuery
What is the most efficient way to deep clone an object in JavaScript?jQuery API DocumentationI want to note that the .clone() method in jQuery only clones DOM elements.
将两个或多个对象的内容合并到第一个对象中。
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
jQuery API Documentation
http://www.cnblogs.com/xgqfrms/p/6942570.html
编辑于 2017-06-04 23:45