集合与 JSON
Map/Set/WeakMap/WeakSet、JSON、data structures。
30 分钟
集合与 JSON
javascript-core 侧重数组;本课覆盖 Map/Set/WeakMap/WeakSet、JSON 序列化边界 与常见数据结构选型。API 层与 nodejs-essentials 大量处理 JSON;react-essentials 用 Set 去重、Map 缓存很常见。
学习目标
- 在 Object vs Map、Array vs Set 之间正确选型
- 理解 WeakMap/WeakSet 的弱引用与 GC 关系
- 安全使用
JSON.parse/JSON.stringify
Map 与 Set
const bySlug = new Map([
['js-core', { title: 'JavaScript 核心' }],
['js-advanced', { title: 'JavaScript 进阶' }],
]);
bySlug.get('js-core');
bySlug.set('react', { title: 'React' });
bySlug.has('react'); // true
const tags = new Set(['frontend', 'javascript', 'frontend']);
tags.size; // 2
tags.add('nodejs');
[...tags];
Map 键可以是任意类型(含对象);Object 键只能是 string/Symbol。频繁增删键值对时 Map 性能更好。
WeakMap / WeakSet
const cache = new WeakMap();
let obj = { id: 1 };
cache.set(obj, { computed: 42 });
// obj = null 后,cache 中条目可被 GC 回收(无强引用)
Weak 集合不可遍历、无 size;适合 DOM 节点关联元数据、私有缓存,避免内存泄漏。
Object 与 Map 选型
| 场景 | 推荐 |
|---|---|
| 固定 shape、JSON 序列化 | 普通 Object |
| 键非字符串、频繁增删 | Map |
| 去重 | Set |
需要 .length 有序列表 | Array |
JSON 序列化
const lesson = {
title: '集合',
meta: { order: 8 },
created: new Date(),
fn: () => {},
};
JSON.stringify(lesson);
// {"title":"集合","meta":{"order":8},"created":"2026-..."}
// fn 被忽略;Date 变 ISO 字符串
JSON.parse('{"a":1}', (key, value) => {
if (key === 'a') return value * 2;
return value;
}); // { a: 2 } — reviver
安全:勿对不可信字符串直接 JSON.parse 后当代码执行;大整数可能精度丢失。
常见数据结构模式
// LRU 简易思路:Map 保持插入顺序
class LRU {
constructor(limit = 100) {
this.limit = limit;
this.map = new Map();
}
get(key) {
if (!this.map.has(key)) return;
const v = this.map.get(key);
this.map.delete(key);
this.map.set(key, v);
return v;
}
set(key, value) {
if (this.map.has(key)) this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.limit) {
const first = this.map.keys().next().value;
this.map.delete(first);
}
}
}