ES6 引入了 Map 和 Set 来解决普通对象和数组的局限性。
Set (唯一值)
删除重复项的最快方法。
javascript
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)。
javascript
const cache = new Map();
const user = { id: 1 };
// 使用对象作为键!
cache.set(user, "用户数据");
console.log(cache.get(user)); // "用户数据"