菜鸟-创作你的创作

JavaScript 中 Set 和 Map 的示例详解

下面给你一份 超清晰、可直接运行的 JavaScript Set 与 Map 示例详解,从基础到高级应用,包含常见用法、容易忽略的细节、以及工程级场景示例。适合学习、面试、项目引用。


🚀 一、Set 的示例详解(唯一值集合)


1️⃣ Set 基本用法

const set = new Set();

set.add(1);
set.add(2);
set.add(2);  // 重复值会被忽略

console.log(set);  // Set { 1, 2 }
console.log(set.size); // 2
console.log(set.has(1)); // true
set.delete(1);
console.log(set.has(1)); // false

特点:


2️⃣ 用 Set 进行数组去重(最常见)

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

console.log(unique);  // [1, 2, 3]

这是前端最常见的 Set 使用场景之一。


3️⃣ Set 对 NaN 的处理示例

const set = new Set([NaN, NaN]);

console.log(set.size); // 1 (NaN === NaN 在 Set 中为 true)

对比数组:

[NaN].includes(NaN); // false


4️⃣ Set 可以存储对象(按引用判断是否相同)

const set = new Set();
const obj = { a: 1 };

set.add(obj);
set.add({ a: 1 }); // 引用不同,被当作新元素

console.log(set.size); // 2


5️⃣ Set 遍历示例

const set = new Set(["a", "b", "c"]);

for (const v of set) {
  console.log(v);
}

set.forEach(v => console.log("foreach:", v));


🔥 6️⃣ 使用 Set 做集合运算(高级示例)

并集

const a = new Set([1, 2]);
const b = new Set([2, 3]);

const union = new Set([...a, ...b]);
console.log(union); // Set {1,2,3}

交集

const intersection = new Set([...a].filter(x => b.has(x)));
console.log(intersection); // Set {2}

差集

const difference = new Set([...a].filter(x => !b.has(x)));
console.log(difference); // Set {1}


🚀 二、Map 的示例详解(键值对哈希结构)


1️⃣ 基本用法

const map = new Map();

map.set("name", "Jack");
map.set("age", 18);

console.log(map.get("name")); // Jack
console.log(map.has("age"));  // true

map.delete("age");

console.log(map.size); // 1


2️⃣ Map 的 key 可以是任意类型(重点)

const map = new Map();

const obj = { id: 1 };
map.set(obj, "this is object");

map.set(() => {}, "function key");
map.set(NaN, "NaN key");

console.log(map);

Object 不能做到这一点(只能用字符串当 key)。


3️⃣ Map 遍历示例

const map = new Map([
  ['a', 1],
  ['b', 2]
]);

for (const [key, value] of map) {
  console.log(key, value);
}

map.forEach((value, key) => {
  console.log("foreach:", key, value);
});


4️⃣ 使用 Map 来统计词频(工程中最常见场景)

const text = "banana";

const freq = new Map();

for (const ch of text) {
  freq.set(ch, (freq.get(ch) || 0) + 1);
}

console.log([...freq]);
// [ ['b',1], ['a',3], ['n',2] ]


5️⃣ 学会用对象当 key(强大示例)

const user = { id: 1 };
const map = new Map();

map.set(user, { loginTime: Date.now() });

console.log(map.get(user));

// 删除对象不会误删其他 key
map.delete(user);

Object 当 key 时按引用判断。


🔥 6️⃣ 实现 LRU Cache(Map 的经典应用)

class LRU {
  constructor(limit = 3) {
    this.limit = limit;
    this.cache = new Map();
  }

  get(key) {
    if (!this.cache.has(key)) return null;

    const value = this.cache.get(key);
    this.cache.delete(key);         // 移除旧位置
    this.cache.set(key, value);     // 插到末尾(最新)
    return value;
  }

  set(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    }

    this.cache.set(key, value);

    if (this.cache.size > this.limit) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
  }
}

const lru = new LRU(2);
lru.set("a", 1);
lru.set("b", 2);
lru.set("c", 3);  // a 被淘汰
console.log([...lru.cache]); // [["b",2],["c",3]]

Map 的 “保持插入顺序” + “快速查询” 完美适合做 LRU。


🚀 三、Set 与 Map 合作示例(高级)


1️⃣ 根据 Map 中的值过滤 Set

const ids = new Set([1, 2, 3, 4]);
const info = new Map([[1, "ok"], [3, "ok"]]);

const filtered = new Set([...ids].filter(id => info.has(id)));

console.log(filtered); // Set {1, 3}


2️⃣ 用 Set 去重 Map 的 value

const users = new Map([
  ['a', 'Tom'],
  ['b', 'Jack'],
  ['c', 'Tom']
]);

const uniqueNames = new Set(users.values());

console.log(uniqueNames); // Set {'Tom','Jack'}


🚀 四、Set 与 Map 的常见陷阱示例


❗1️⃣ Set 对对象不去重(按引用判断)

new Set([{a:1}, {a:1}]).size; // 2


❗2️⃣ Map 中 key 是对象时必须保留引用

const map = new Map();
map.set({a:1}, 123);

map.get({a:1}); // undefined,因为不是同一个引用


❗3️⃣ JSON 无法直接序列化 Set/Map

JSON.stringify(new Set([1,2])); // {}

正确做法:

JSON.stringify([...new Set([1,2])]); // [1,2]

退出移动版