JavaScript Set

【 JavaScript 】Set 筆記

延續上一篇:【 JavaScript 】Map 筆記,這篇就來筆記一下 Set 的用法吧!

JavaScript Set

1. 特性

  • Set 內的元素不重複
  • has method 可以快速檢查 Set 是否包含某元素,效能會比使用陣列的 Array.prototype.includes 來得好

2. 宣告 Set

基本上使用 new Set(),argument 可以為空或是 array,如果是 array,會自動把重複的元素過濾掉:

const set = new Set();
console.log(set);
// Set(0) {}

const set1 = new Set([1, 2, 3]);
console.log(set1);
// Set(3) { 1, 2, 3 }

const set2 = new Set([1, 1, 2, 2]);
console.log(set2);
// Set(2) { 1, 2 }

3. 操作 Set

const arr = [1, 5, 4, 3, 2];
const set = new Set(arr);

console.log(set.size);
// 5

console.log(set.has(1));
// true
console.log(set.has(6));
// false

set.add(7);
set.add('hello world');
console.log(set);
// Set(7) { 1, 5, 4, 3, 2, 7, 'hello world' }

set.delete('hello world');
console.log(set);
// Set(6) { 1, 5, 4, 3, 2, 7 }

set.clear()
console.log(set)
// Set(0) {}

4. 迭代 Set

const arr = [1, 2, 'hello', { name: 'Jimmy' }];
const set = new Set(arr);

// method 1
for (const item of set) {
  console.log(item);
}

// method 2
for (const item of set.keys()) {
  console.log(item);
}

// method 3
for (const item of set.values()) {
  console.log(item);
}

// method 4
set.forEach((s) => console.log(s));

/* 以上皆會 console 出:
1
2
hello
{ name: 'Jimmy' }
*/

5. 轉換成 Array

const set = new Set([1, 2, 5]);

console.log(Array.from(set));
// [ 1, 2, 5 ]
console.log([...set]);
// [ 1, 2, 5 ]

參考資料

Set – JavaScript – MDN Web Docs – Mozilla

看完這篇文章是不是想換工作了呢(咦?那就千萬別錯過 2024 職涯博覽會!想換工作的,有機會在博覽會遇見更好的另一半,不想換工作的,有機會在博覽會遇見更好的工作!趕快點擊下面的 banner,拯救你的人生!!!https://s.yourator.co/jimmy

如果覺得我的文章有幫助的話,歡迎幫我的粉專按讚哦~謝謝你!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top