1、对象赋值
两个对象指向的是同一个存储空间,无论哪个对象发生改变,其实都是改变的存储空间的内容,因此,两个对象是联动的。
2、浅拷贝
浅拷贝:只进行一层关系的拷贝。
循环遍历对象
function shallowClone(o){
let obj={}
for(let key in o){
obj[key]=o[key]
}
return obj
}
Object.assign(target,source)
let a={name:'xxxx'}
let b=Object.assign({},a)
b.name='hhhh'
console.log(a.name); //"xxxx"
Object.assign可以理解为对象中的属性是基础类型,Object.assign执行的是深拷贝;对象中的属性是引用类型,Object.assign执行的是浅拷贝。`
let source = {
a: {
b: 1
},
c: 1
};
let target = Object.assign({}, source);
source.a.b = 2;
source.c = 3
console.log('source',source)
console.log('target',target)
ES6
let a={name:'xxxx'}
let b={...a}
b.name='hhhh'
console.log(a.name); //"xxxx"
3、深拷贝
深拷贝:在浅拷贝的基础上,进行多层遍历拷贝。
手写递归
function deepCopy(source){
if (typeof source != "object") {
return source;
}
if (source == null) {
return source;
}
var newObj = source.constructor === Array ? [] : {}; //开辟一块新的内存空间
for (var i in source) {
newObj[i] = deepCopy(source[i]); //通过递归实现深层的复制
}
return newObj;
}
JSON.stringify()
function cloneJSON(source) {
return JSON.parse(JSON.stringify(source));
}