Skip to content

Commit

Permalink
Merge branch 'writing'
Browse files Browse the repository at this point in the history
  • Loading branch information
ihengshuai committed Sep 10, 2023
2 parents 71f16c2 + 801cf47 commit 6f9e5e7
Showing 1 changed file with 26 additions and 15 deletions.
41 changes: 26 additions & 15 deletions docs/article/2019/js-copy.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,22 +216,33 @@ console.log(arr, arr4);

递归方法实现深度克隆原理:遍历对象、数组直到里边都是基本数据类型,然后再去复制,就是深度拷贝

```js
function deepCopy(target, origin) {
target = target || {};
let toStr = Object.prototype.toString,
arrStr = "[object Array]";
for (let prop in origin) {
if (origin[prop] !== "null" && typeof origin[prop] == "object") {
toStr.call(origin[prop]) == arrStr
? (target[prop] = [])
: (target[prop] = {});
deepCopy(target[prop], origin[prop]);
} else {
target[prop] = origin[prop];
```ts
function deepCopy(from: any, map: any = new Map()) {
const isObject = (obj: any): obj is Object =>
Object.prototype.toString.call(obj) === "[object Object]" ||
Object.prototype.toString.call(obj) === "[object Array]";

if (!isObject(from)) return from;
let res: any = Array.isArray(from) ? [] : {};

// 有缓存时不用递归,解决循环引用问题
if (map.get(from)) res = map.get(from);
else {
// 缓存当前对象
map.set(from, res);
for (const key of [
...Object.keys(from),
...Object.getOwnPropertySymbols(from),
]) {
const val = from[key];
if (isObject(val)) {
res[key] = deepCopy(val, map);
} else {
res[key] = val;
}
}
}
return target;
return res;
}
```

Expand All @@ -243,7 +254,7 @@ let a = {
say: function() {},
m: Symbol(1)
};
const b = deepCopy({}, a)
const b = deepCopy(a)
b.age = 12
b.arr[1] = 4
b.m = Symbol(2)
Expand Down

0 comments on commit 6f9e5e7

Please sign in to comment.