deepClone深拷贝

//空间换时间

1
2
3
4
5
6
7
8
9
10
export default function memo(func, hasher){
const cache = {};
return function(...args){
let key = ""+(hasher ? hasher(...args) : args[0])
if(!cache[key]){
cache[key] = function(...args);
}
return cache[key]
}
}

JSON.parse(JSON.stringfy())
实现深拷贝—缺陷:不能拷贝Symbol、函数、循环引用。

深拷贝——简介版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function deepClone = obj => {
if(typeof obj != "object" || obj === null){
return obj;
}
let result;
if(base instanceof Array){
result = [];
} else {
result = {};
}
for(let item in base){
if(base.hasOwnProperty(item)){
result[item] = deepClone(base[item])
}
}
return result;
}

深拷贝—— 可以解决循环引用

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
export default deepClone = base =>{
const baseStack=[];
const targetStack = [];
let _clone = base => {
if(typeof base != "object" || base === null){
return base;
}
let target = {};
if(Array.isArray(base)){
target = [];
}
const index = baseStack.indexOf(base);
if(index != -1){
return targetStack[index];
}

baseStack.push(base);
targetStack.push(target);

for(let i in base){
target[i] = _clone(base[i]);_
}
return target;
}_
}