js - copy
ru shui 2021-09-10 Less than 1 minute
# 浅拷贝
function shallowCopy(obj) {
if (!obj) return obj
const result = {}
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
result[key] = obj[key]
}
}
return result
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# API 提供的浅拷贝功能
Object.assign()
lodash.clone()
- ... 展开运算符
Array.prototype.concat
Array.prototype.slice
# 深拷贝
# 深度优先版深拷贝
function deepCopy(obj) {
if (!isPlainObject(obj)) return obj
const isArray = Array.isArray
const result = isArray(obj) ? [] : {}
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
const element = obj[key]
result[key] = isPlainObject(element) ? deepCopy(element) : element
}
}
return result
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 广度优先深拷贝
const isArray = Array.isArray
const result = isArray(obj) ? [] : {}
const helper = (obj, key, value, queue) => {
if (isPlainObject(value)) {
queue.push([obj, key, value])
} else {
obj[key] = value
}
}
function deepCopyBFS(obj, queue = []) {
if (!isPlainObject(obj)) return obj
if (obj instanceof Date) return new Date(obj)
if (obj instanceof RegExp) return new RegExp(obj)
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
helper(obj, key, obj[key], queue)
}
}
while (queue.length) {
const [obj, key, value] = queue.shift()
obj[key] = deepCopyBFS(value, queue)
}
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
26
27
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
# json 实现深拷贝
const copy = obj => JSON.parse(JSON.stringify(obj))
1
注意:对于一些不可以序列化的属性会出现错误。