⚡Map vs Set:5 分钟吃透键值对与唯一值

44 阅读1分钟

1 基础

1.1 Map 键值对

const m = new Map([['a', 1], ['b', 2]]);
m.set('c', 3);
console.log(m.get('c')); // 3

1.2 Set 唯一值

const s = new Set([1, 2, 2]);
console.log([...s]); // [1, 2]

2 高阶用法

2.1 Map 缓存

const cache = new Map();
function fetchUser(id) {
  if (cache.has(id)) return cache.get(id);
  const user = 'Alice';
  cache.set(id, user);
  return user;
}

2.2 Set 去重

const arr = [1, 2, 2, 3];
const unique = [...new Set(arr)]; // [1, 2, 3]

2.3 Map 分组

const list = [{type: 'A', v: 1}, {type: 'B', v: 2}];
const group = list.reduce((m, o) => {
  (m[o.type] ||= []).push(o);
  return m;
}, {});

2.4 Set 交集

const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const inter = [...a].filter(x => b.has(x)); // [2, 3]

3 实战场景

3.1 用户权限 Map

const roles = new Map([
  ['admin', ['read', 'write']],
  ['guest', ['read']]
]);
roles.get('admin').includes('write'); // true

3.2 标签去重 Set

const tags = ['js', 'css', 'css', 'html'];
const uniqueTags = [...new Set(tags)];

3.3 缓存命中 Map

const cache = new Map();
function getData(key) {
  if (cache.has(key)) return cache.get(key);
  const data = 'data';
  cache.set(key, data);
  return data;
}

3.4 交集 Set

const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const inter = [...a].filter(x => b.has(x)); // [2, 3]

3.5 管道 Map

const pipeline = new Map([
  ['step1', (x) => x + 1],
  ['step2', (x) => x * 2]
]);
let res = 5;
pipeline.forEach(fn => res = fn(res));
console.log(res); // 12

4 性能对比

操作MapSet备注
插入O(1)O(1)哈希表
查找O(1)O(1)哈希表
遍历O(n)O(n)遍历所有元素

5 一句话总结

Map 做键值对缓存,Set 做唯一值集合,两者都是哈希表实现,性能 O(1)。