返回
Set和Map的实际应用,让你恍然大悟
前端
2024-01-02 23:18:37
一、Set
Set是一种无序且不重复元素的集合。与数组不同,Set不会允许重复的元素。Set的典型用途是确保元素的唯一性,例如,它可用于去除数组中的重复元素。
1. 去重
最常见的应用是去除数组中的重复元素。
const numbers = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
2. 检查元素是否存在
Set还可用于快速检查元素是否存在。
const set = new Set([1, 2, 3, 4, 5]);
console.log(set.has(2)); // true
console.log(set.has(6)); // false
3. 求交集、并集和差集
Set提供了交集(intersection)、并集(union)和差集(difference)等操作。
const set1 = new Set([1, 2, 3]);
const set2 = new Set([3, 4, 5]);
// 交集
const intersection = new Set([...set1].filter(x => set2.has(x)));
console.log(intersection); // Set {3}
// 并集
const union = new Set([...set1, ...set2]);
console.log(union); // Set {1, 2, 3, 4, 5}
// 差集
const difference = new Set([...set1].filter(x => !set2.has(x)));
console.log(difference); // Set {1, 2}
二、Map
Map是一种键值对的数据结构。它允许我们将键映射到值,并可以通过键快速检索值。Map的典型用途是存储相关数据,例如,它可用于存储用户ID与用户名的映射。
1. 存储键值对
Map最基本的功能就是存储键值对。
const map = new Map();
map.set('name', 'John Doe');
map.set('age', 30);
map.set('city', 'New York');
console.log(map.get('name')); // 'John Doe'
2. 遍历键值对
Map提供了遍历键值对的方法。
const map = new Map([
['name', 'John Doe'],
['age', 30],
['city', 'New York']
]);
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
// 输出:
// name: John Doe
// age: 30
// city: New York
3. 检查键是否存在
Map还提供了检查键是否存在的方法。
const map = new Map([
['name', 'John Doe'],
['age', 30],
['city', 'New York']
]);
console.log(map.has('name')); // true
console.log(map.has('country')); // false
4. 删除键值对
Map也提供了删除键值对的方法。
const map = new Map([
['name', 'John Doe'],
['age', 30],
['city', 'New York']
]);
map.delete('age');
console.log(map.get('age')); // undefined
三、总结
Set和Map是JavaScript中非常有用的数据结构。它们提供了多种操作,可以帮助我们更有效地管理数据。希望这篇文章能帮助你更好地理解和使用Set和Map。