deepClone【深度克隆】
描述
深度克隆。 可以使用,你也可以去使用 lodash-es 中的 clone 方法 (opens new window)
# 1.示例
import { deepClone } from 'sf-utils2'
const user = {
name: '蔡徐坤',
id: '1',
list: [],
obj: {
id: '---',
hos: {
location: {
name: '卫生院'
}
},
say() {
console.log(this)
}
}
}
console.log('开始')
const userCopy = deepClone(user)
console.log(userCopy)
console.log(userCopy.list === user.list) // false
// 结果:
// {
// name: '张洪文',
// id: '1',
// list: [],
// obj: {
// id: '---',
// hos: {
// location: {
// name: '卫生院'
// }
// }
// }
// }
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
35
36
37
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
35
36
37
:::
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|---|---|---|---|
| target | 原数据 | Any | 是 |
# 3.源码
import _typeof from '@/base/_typeof'
/**
* 浅拷贝/深拷贝
* @param {Object} obj 对象/数组
* @param {Boolean} isDeep 是否深度拷贝 默认是
* @return {Object}
*/
function deepClone(obj, isDeep = true) {
function getNativeCtor(val, args) {
const Ctor = val.__proto__.constructor
return args ? new Ctor(args) : new Ctor()
}
function handleValueClone(item, isDeep) {
return isDeep ? copyValue(item, isDeep) : item
}
function copyValue(val, isDeep) {
if (val) {
switch (_typeof(val)) {
case 'Object': {
const restObj = Object.create(val.__proto__)
Object.keys(val).forEach(key => {
restObj[key] = handleValueClone(val[key], isDeep)
})
return restObj
}
case 'Date':
case 'RegExp': {
return getNativeCtor(val, val.valueOf())
}
case 'Array':
case 'Arguments': {
const restArr = []
val.map(item => {
restArr.push(handleValueClone(item, isDeep))
})
return restArr
}
case 'Set': {
const restSet = getNativeCtor(val)
restSet.forEach(item => {
restSet.add(handleValueClone(item, isDeep))
})
return restSet
}
case 'Map': {
const restMap = getNativeCtor(val)
restMap.forEach(item => {
restMap.set(handleValueClone(item, isDeep))
})
return restMap
}
}
}
return val
}
return copyValue(obj, isDeep)
}
export default deepClone
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
上次更新: 2023/06/24, 19:35:48