Comments (2)
待读文章:
from blog.
递归实现一个深拷贝
const target = {
field1: 1,
field2: undefined,
field3: {
child: "child",
},
field4: [2, 4, 8],
};
target.target = target;
实现:
function clone(target, map = new WeakMap()) {
if (typeof target === "object") {
let cloneTarget = Array.isArray(target) ? [] : {};
if (map.get(target)) {
return;
map.get(target);
}
map.set(target, cloneTarget);
for (const key in target) {
cloneTarget[key] = clone(target[key], map);
}
return;
cloneTarget;
} else {
return;
target;
}
}
深拷贝也是递归常考的例子
每次拷贝发生的事:
- 检查 map 中有无克隆过的对象
- 有,直接返回
- 没有, 将当前对象作为 key,克隆对象作为 value 进行存储
- 继续克隆
在这段代码中我们使用了 weakMap ,用来防止因循环引用而出现的爆栈。
from blog.
Related Issues (20)
- 【JavaScript】模块化 HOT 1
- 【JavaScript】错误异常与捕获
- 【JavaScript】async 和 await
- 【React】setState的执行机制 HOT 1
- 【React】React的事件机制
- 可靠React组件设计的7个准则
- 【JavaScript】深入EventLoop和浏览器渲染、帧动画、空闲回调的关系
- 【网络】options 请求、简单请求与复杂请求 HOT 1
- 【JavaScript】Fetch
- 【JavaScript】循环遍历 in JavaScript
- 【JavaScript】数组拍平与数组去重
- 【JavaScript】数组对象与 arguments
- 浏览器中加载JavaScript的方式
- ES6 基础
- 手写实现 call 和 apply
- 网络原理学习
- Web Workers
- Reducer
- 2022 学习记录
- TypeScript基础学习
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog.