对象拷贝
在JavaScript中,对象拷贝分为两种:浅拷贝、深拷贝
浅拷贝
将一个对象中的值复制到另一个对象中(不考虑属性中是否有引用类型),example:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30var a = {
name: 'jack',
age: 20
}
function copy(obj) {
var newObj = new Object();
for(let attr in obj) {
newObj[attr] = obj[attr];
}
return newObj;
}
var newObj = copy(a);
console.log(newObj.name);
var b = {
name: 'lin',
age: 21,
bestfriends: {
name: 'l',
age: 21
}
}
var c = copy(b);
console.log('before update b:' + b.name + ' ' + b.age + ' ' + b.bestfriends.name);
console.log('before update c:' + c.name + ' ' + c.age + ' ' + c.bestfriends.name);
c.bestfriends.name='ll'; //修改c中的bestfriends属性
console.log('after update b:' + b.name + ' ' + b.age + ' ' + b.bestfriends.name); //结果b中的也会随之更新
console.log('after update c:' + c.name + ' ' + c.age + ' ' + c.bestfriends.name);
为了解决在对象拷贝过程中将对象中的对象属性独立拷贝出来,所以有了深拷贝
深拷贝
1.使用递归实现拷贝1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26function depthCopy(obj) {
if(typeof obj !== 'object') {
return obj;
}
var newObj = {};
for(let attr in obj) {
newObj[attr] = depthCopy(obj[attr]);
}
return newObj;
}
var b = {
name: 'lin',
age: 21,
bestfriends: {
name: 'l',
age: 21
}
}
var c = depthCopy(b);
console.log('before update b.bestfriends.name: ' + b.bestfriends.name)
console.log('before update c.bestfriends.name: ' + c.bestfriends.name)
c.bestfriends.name = 'jacklincao' //修改c.bestfrinds对象
console.log('after update b.bestfriends.name: ' + b.bestfriends.name) //b中的不变
console.log('after update c.bestfriends.name: ' + c.bestfriends.name) //c中的变了,说明b和c现在没有指向同一个对象,实现了深复制
2.使用JSON序列化1
2
3
4
5
6
7
8
9
10
11
12
13
14
15var b = {
name: 'lin',
age: 21,
bestfriends: {
name: 'l',
age: 21
}
}
var c = JSON.parse(JSON.stringify(b));
console.log('before update b.bestfriends.name: ' + b.bestfriends.name)
console.log('before update c.bestfriends.name: ' + c.bestfriends.name)
c.bestfriends.name = 'jacklincao' //修改c.bestfrinds对象
console.log('after update b.bestfriends.name: ' + b.bestfriends.name) //b中的不变
console.log('after update c.bestfriends.name: ' + c.bestfriends.name) //c中的变了,说明b和c现在没有指向同一个对象,实现了深复制