数据掌握2026年1月24日星期六

Map 与 Set

现代 ES6 数据结构。

广告

查看赞助商以支持 JS Fruggal。

ES6 引入了 MapSet 来解决普通对象和数组的局限性。

Set (唯一值)

删除重复项的最快方法。

const emails = ["[email protected]", "[email protected]", "[email protected]"];
const uniqueEmails = [...new Set(emails)];
console.log(uniqueEmails); // ["[email protected]", "[email protected]"]

Map (更好的键值对)

为什么用 Map 而不是 Object?
  • 键可以是任何类型(对象、函数),不仅仅是字符串。
  • 保留插入顺序。
  • 具有内置的 .size 属性(不需要 Object.keys().length)。
const cache = new Map();
const user = { id: 1 };

// 使用对象作为键!
cache.set(user, "用户数据");

console.log(cache.get(user)); // "用户数据"
广告

查看赞助商以支持 JS Fruggal。