-
Notifications
You must be signed in to change notification settings - Fork 1
/
clone.js
34 lines (33 loc) · 872 Bytes
/
clone.js
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
30
31
32
33
34
function isTypeOf(obj, type) {
const typeMap = {
array: "Array",
object: "Object",
function: "Function",
string: "String",
null: "Null",
undefined: "Undefined",
boolean: "Boolean",
number: "Number"
};
return Object.prototype.toString.call(obj) === `[object ${typeMap[type]}]`;
}
/**深度优先遍历拷贝 */
function DFSdeepClone(param, visitList = []) {
if (isTypeOf(param, "function")) {
return eval(`(${param.toString()})`);
}
if (!isTypeOf(param, "array") && !isTypeOf(param, "object")) {
return param;
}
if (visitList.includes(param)) {
return visitList[visitList.indexOf(param)];
}
visitList.push(param);
let res = isTypeOf(param, "array") ? [] : {};
for (const key in param) {
if (param.hasOwnProperty(key)) {
res[key] = DFSdeepClone(param[key], visitList);
}
}
return res;
}