浅拷贝
浅拷贝只拷贝一层,深层次的对象只拷贝引用
var obj = {
name: 'zhangsan',
age: 18,
omg: {
name: 'omg'
}
}
var ob = {};
for (var i in obj) {
ob[i] = obj[i]
}
console.log(ob);
拷贝对象ob
ob深层对象omg改变会改变原始对象obj中的omg
var obj = {
name: 'zhangsan',
age: 18,
omg: {
name: 'omg'
}
}
var ob = {};
for (var i in obj) {
ob[i] = obj[i]
}
ob.omg.name = 'ob';
ob.name = 'omg';
console.log(ob)
console.log(obj);
浅拷贝会改变深层对象
ES6 新增的浅拷贝方法 Object.assign
var obj = {
name: 'zhangsan',
age: 18,
omg: {
name: 'omg'
}
}
var ob = {};
Object.assign(ob,obj);
console.log(ob)
对象浅拷贝方法assign
利用递归进行对象的深拷贝
var obj = {
name: 'zhangsan',
age: 18,
omg: {
name: 'omg'
},
yy: [1,2,3]
}
var ob = {};
function deepCopy(newO,oldO) {
for (var k in oldO) {
var item = oldO[k];
if (item instanceof Array) {
newO[k] = [];
deepCopy(newO[k],item);
} else if (item instanceof Object) {
newO[k] = {};
deepCopy(newO[k],item);
} else {
newO[k] = item;
}
}
}
deepCopy(ob,obj);
ob.omg.name = 'ccc';
ob.yy.push(1,2);
console.log(ob);
console.log(obj);
深拷贝
网友评论