集合

集合 在 JavaScript

2 個練習

關於 集合

在 JavaScript 中,集合是一種類似清單的資料結構,只能包含唯一的原始型別及/或物件參考。

集合必須透過集合建構函式建立;建立時傳入一個陣列,就能替集合設定初始值。

const emptySet = new Set();
const setWithInitialValues = new Set(['hello', 'world']);

新增與移除元素

如果某個值與集合中的任何元素嚴格相等,就無法加入這個集合。

const set = new Set();
set.add(10);
set.add(10); // 10 is strictly equal to 10, so it can't be added again
set.size;
//=> 1;

set.has(10);
//=> true
set.delete(10);
//=> true; 10 was removed
set.delete(10);
//=> false; 10 is not in the set, so nothing happened

const obj = { color: 'magenta' };
const eerilySimilarObj = { color: 'magenta' };

set.add(obj);
set.add(eerilySimilarObj); // obj and eerilySimilarObj reference different objects, so they can both be added
set.size;
//=> 2

set.clear();
set.size;
//=> 0

在集合與陣列之間轉換

陣列透過集合建構函式轉換成集合。集合則可以用展開語法或Array.from()轉換成陣列。

const arrayWithDuplicates = [7, 3, 3, 9, 3];
const arrayWithoutDuplicates = [...new Set(arrayWithDuplicates)]; // [7, 3, 9]
const anotherArrayWithoutDuplicates = Array.from(new Set(arrayWithDuplicates)); // [7, 3, 9]

疊代

集合是一種鍵值集合,意思是它的元素以鍵來索引,並且可以依照插入順序疊代。由於集合元素的_鍵_與_值_相同,Set.keys()和Set.values()可以互換使用。

const apples = ['Granny Smith', 'Honey Crisp', 'Royal Gala'];
const appleSet = new Set(apples);

for (let apple of appleSet.keys()) {
  console.log(apple);
}
// 'Granny Smith'
// 'Honey Crisp'
// 'Royal Gala'

for (let apple of appleSet.values()) {
  console.log(apple);
}
// 'Granny Smith'
// 'Honey Crisp'
// 'Royal Gala'

for (let apple of appleSet.entries()) {
  console.log(apple);
}
// ['Granny Smith', 'Granny Smith']
// ['Honey Crisp', 'Honey Crisp']
// ['Royal Gala', 'Royal Gala']

查找效能與陣列的比較

當我們選擇用集合(而不是陣列)來存放一組資料時,通常是因為這些值必須是唯一的。不過,既然用陣列也能確保唯一性,可能就不容易看出為什麼要改用集合。

簡單來說,集合是為了搜尋而最佳化的,陣列則不是。陣列的搜尋方法(例如Array.indexOf())的執行時間會隨著陣列大小呈線性成長;也就是說,陣列裡的元素越多,搜尋所需的時間就越長。相對地,集合的搜尋方法執行時間是固定的,無論集合多大都維持不變。

不過在實務上,除非資料量非常龐大,否則這點效能差異微乎其微。

透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 集合