JS的集合
- 前言
- 一、集合
- 二、基本使用
- 1. 創建集合
- 2. 添加元素
- 3. 刪除元素
- 4. 檢查元素
- 5. 清空集合
- 6. 集合的大小
- 三、擴展使用
- 1. 遍歷集合
- 2. 從數組創建集合
- 3. 集合的應用場景
- 四、總結
前言
JS里對于集合的簡單介紹
同數學的集合,有無序性、唯一性
注意:無法獲取某個元素的下標,因為無序性
所以對于某些情況:
例如:求兩數之和時,需要使用到下標,此時不適合使用集合,可以使用Map
一、集合
在 JavaScript 中,集合(Set)是一種非常有用的數據結構,用于存儲獨特的值,這些值可以是原始值或對象引用。集合的主要特點是它保證了集合中所有的值都是唯一的,因此在處理需要去重的數據時非常有效。
二、基本使用
1. 創建集合
可以通過 new Set() 來創建一個新的集合
// 創建空集合
const set1 = new Set();// 用數組初始化集合
const set2 = new Set([1, 2, 3, 3]); // 自動去重,結果為{1, 2, 3}// 用字符串初始化
const set3 = new Set("hello"); // {"h", "e", "l", "o"}// 用DOM對象初始化
const lis = document.querySelectorAll('li');
const setLi = new Set(lis);
2. 添加元素
使用 add() 方法向集合中添加元素
mySet.add(1);
mySet.add(2);
mySet.add(3);
console.log(mySet); // Set { 1, 2, 3 }
如果嘗試添加重復的元素,集合會自動忽略
mySet.add(2);
console.log(mySet); // Set { 1, 2, 3 },2 只會出現一次
3. 刪除元素
使用 delete() 方法從集合中刪除元素
mySet.delete(2);
console.log(mySet); // Set { 1, 3 }
4. 檢查元素
可以使用 has() 方法檢查集合中是否包含特定元素
console.log(mySet.has(1)); // true
console.log(mySet.has(2)); // false
5. 清空集合
使用 clear() 方法可以移除集合中的所有元素
mySet.clear();
console.log(mySet); // Set {}
6. 集合的大小
使用 size 屬性可以獲取集合中元素的數量:
const mySet = new Set(1, 2, 3)
console.log(mySet.size); // 3
三、擴展使用
1. 遍歷集合
可以使用 forEach 方法或 for…of 循環遍歷集合中的元素:
mySet.add(1);
mySet.add(2);mySet.forEach(value => {console.log(value); // 輸出 1 和 2
});for (const value of mySet) {console.log(value); // 輸出 1 和 2
}
2. 從數組創建集合
可以將數組傳遞給 Set 構造函數,以自動去重數組中的元素
const uniqueArray = new Set([1, 2, 2, 3, 4]);
console.log(uniqueArray); // Set { 1, 2, 3, 4 }
如果需要將集合轉換重新為數組,可以使用 Array.from() 或擴展運算符( … )
const uniqueArrayBack = Array.from(uniqueArray);
console.log(uniqueArrayBack); // [1, 2, 3, 4]const uniqueArrayBack2 = [...uniqueArray];
console.log(uniqueArrayBack2); // [1, 2, 3, 4]
3. 集合的應用場景
- 去重: 當你需要從一個數組中去掉重復的元素時,可以使用 Set。
- 檢查唯一性: 快速檢查一個元素是否已經在集合中。
- 集合運算: Set 也可以被用來實現集合運算,例如交集、并集和差集等。
示例:集合運算
下面的示例展示了如何使用集合來計算兩個數組的交集
function intersect(arr1, arr2) {const set1 = new Set(arr1);const set2 = new Set(arr2);const intersection = [];set2.forEach(value => {if (set1.has(value)) {intersection.push(value);}});return intersection;
}const array1 = [1, 2, 3, 4];
const array2 = [3, 4, 5, 6];
console.log(intersect(array1, array2)); // 輸出: [3, 4]
四、總結
JavaScript 中的集合(Set)提供了一種簡單且高效的方式來處理具有唯一特性的值。它的易用性和強大功能使其在處理數據去重、唯一性檢查和集合運算等方面非常有用。通過掌握 Set 的基本特性和方法,可以在 JavaScript 編程中更好地處理數據。