题目:浅复制和深复制?怎样实现深复制?
出题人:阿里巴巴新零售技术质量部
参考答案:
参考代码;
const isObject = (item)=>{
return Object.prototype.toString.call(item) === '[object Object]';
}
const isArray = (item)=>{
return Object.prototype.toString.call(item) === '[object Array]';
}
const deepClone=(obj)=>{
const cloneObj=isArray(obj)?[]:isObject(obj)?{}:'';
for(let key in obj){
if(isObject(obj[key])||isArray(obj[key])){
Object.assign(cloneObj,{
[key]: deepClone(Reflect.get(obj,key))
});
}
else{
cloneObj[key] = obj[key];
}
}
return cloneObj;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
PS:可以处理这样的格式,仅处理了对象类型和数组类型
const obj111 ={
a:1,
b:{
c:2,
d:{
e:3
},
f:[1,{a:1,b:2},3]
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10