Purpose: Store an unordered, unique set of values, which can be used for operations such as deduplication, filtering, and sorting.
1. Create an empty Set instance.
const myset = new set();
2. Use the add() method to add elements to the Set.
mySet.add("Apple");
mySet.add("Banana");
mySet.add("Orange");
3. The order of the elements in the Set is unordered, but each element is unique.
console.log(mySet); // 输出:Set { 'Apple', 'Banana', 'Orange' }
4. You can use the size attribute to get the number of elements in the Set.
console.log(mySet.size); // 输出:3
5. Use the has() method to check whether the Set contains the specified element.
console.log(mySet.has("Banana")); // 输出:true
console.log(mySet.has("Grapes")); // 输出:false
6. Use the delete() method to delete the specified element from the Set.
mySet.delete("Orange");
console.log(mySet); // 输出:Set { 'Apple', 'Banana' }
7. Use the clear() method to clear the entire Set.
mySet.clear();
console.log(mySet); // 输出:Set {}
8. Traverse the Set: Use the forEach() method of Set to traverse each element in the Set.
const mySet = new Set([1, 2, 3]);
mySet.forEach((value) => {
console.log(value);
});
9. Convert Set to Array. A Set can be converted to an array using the spread operator (...) or the Array.from() method.
const mySet = new Set([1, 2, 3, 4, 5]);
// 使用扩展运算符
const myArray = [...mySet];
// 使用Array.from()
const myArray = Array.from(mySet);
console.log(myArray); // 输出:[1, 2, 3, 4, 5]
10. Convert Set to String. You can first convert the Set to an array and then use the array's join() method to convert it to a string.
const mySet = new Set(["Apple", "Banana", "Orange"]);
const myArray = Array.from(mySet);
const myString = myArray.join(", ");
console.log(myString); // 输出:"Apple, Banana, Orange"
11. Convert Set to Object. You can first convert the Set to an array and then use the reduce() method to convert it to an object.
const mySet = new Set([
{ id: 1, name: "Apple" },
{ id: 2, name: "Banana" },
{ id: 3, name: "Orange" },
]);
const myArray = Array.from(mySet);
const myObject = myArray.reduce((obj, item) => {
obj[item.id] = item.name;
return obj;
}, {});
console.log(myObject); // 输出:{ 1: "Apple", 2: "Banana", 3: "Orange" }