以下是我写的简单的递归方式的深拷贝。
function copy(source) {
var key, target
if (type(source) === "array") {
target = []
for (key = 0; key < source.length; key++) {
if (type(source[key]) === "array" || "object") {
target[key] = copy(source[key])
} else if (source[key] !== undefined) target[key] = source[key]
}
} else if (type(source) === "object") {
target = {}
for (key in source) {
if (type(source[key]) === "array" || "object") {
target[key] = copy(source[key])
} else if (source[key] !== undefined) target[key] = source[key]
}
}
return target
}
1
bumz 2018 年 2 月 10 日
|
2
ulala 2018 年 2 月 10 日 via iPad
if (type(source[key]) === "array" || "object") {
这是要表达什么? |
3
onyourroad OP @bumz 看不到。。
|
4
iFun 2018 年 2 月 10 日
去看下 lodash 怎么写的 deepcopy
|
5
sneezry 2018 年 2 月 10 日 via iPhone
如果只考虑数组和对象的话,有个很 tricky 的办法
newObj = JSON.parse(JSON.stringify(obj)) 递归的话最底层是基本类型,string 啊 number 啊 boolean 啊 null 啊什么的,如果是这些类型 copy 要返回数据本身。 |
6
Cbdy 2018 年 2 月 10 日 via Android
单层次的
对象 const t = { ...s } 数组 const t = [ ...s ] |
7
bumz 2018 年 2 月 10 日
|
8
bumz 2018 年 2 月 10 日 简单地说,深拷贝等价于遍历树,不用递归就是 non-recursive tree traversal
|
9
bumz 2018 年 2 月 10 日
不过这个假设对象有循环引用就不行了,需要加一个判回
|
10
onyourroad OP @bumz 谢谢了
|