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
function clone(obj) {
if (typeof obj === 'object') {
if (obj instanceof Array) {
let res = []
for (let index = 0; index < obj.length; index++) {
res[index] = clone(obj[index])
}
return res
} else if (obj instanceof Object) {
let res = {}
for (const key in obj) {
res[key] = clone(obj[key])
}
return res
}
// 这里还可以考虑其他特殊类型例如date regex
} else {
return obj
}
}
console.log('my')
var obj1 = [12, { a: 11, b: 22 }, 5]
var obj2 = clone(obj1)
obj2[1].a += 5
console.log(obj1, obj2)