1
11
javascript 克隆对象/数组的方法 clone()
1
demo:
code:
1 var Obj;
2 let clone = (Obj) => {
3 var buf;
4 if (Obj instanceof Array) {
5 buf = [];
6 var i = Obj.length;
7 while (i--) {
8 buf[i] = clone(Obj[i]);
9 console.log(`Array buf[k] = ${buf[i]}`);
10 console.log(`Array buf[k] = ${buf[i]}`);
11 }
12 console.log(`Array = ${buf}`);
13 return buf;
14 }else if(Obj instanceof Object){
15 buf = {};
16 for (var k in Obj) {
17 buf[k] = clone(Obj[k]);
18 console.log(`Object buf[k] = ${buf[k]}`);
19 }
20 console.log(`Object = ${buf}`);
21 return buf;
22 }else {
23 console.log(`Other = ${Obj}`);
24 return Obj;
25 }
26 }
27 let obj = {name: "xgqfrms", age: 23}
28 // let arr = [{name: "xgqfrms"},{age: 23}];
29 let arr = ["name", "xgqfrms", "age", 23];
30 let str = `xgqfrms`;
31
32 let o = clone(obj);
33 console.log(`\n\nTest obj = ${o}`);
34
35 let a = clone(arr);
36 console.log(`\n\nTest arr = ${a}`);
37
38 let s = clone(str);
39 console.log(`\n\nTest str = ${s}`);
1
1
1
1
1
1
1
1