Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cấu trúc dữ liệu Set (Set Data Structure) trong JavaScript

Set là kiểu dữ liệu trừu tượng (Abstract Data Type) lưu trữ **giá trị duy nhất** (unique values), **không có thứ tự cụ thể** (unordered - mặc dù ES6 giữ insertion order), **không cho phép trùng lặp**.

Là triển khai máy tính của khái niệm **tập hợp hữu hạn (finite set)** trong toán học. Khác với Array/List (truy cập bằng index), Set thường dùng để **kiểm tra thành viên (membership test)**: "Giá trị X có trong tập hợp không?".

Đặc điểm chính

Đặc điểmMô tả
Unique valuesKhông cho phép duplicate. Thêm giá trị đã có → bỏ qua.
No indexKhông truy cập bằng vị trí (arr[0]). Chỉ duyệt hoặc has().
Insertion order (ES6)ES6 Set giữ thứ tự thêm vào. Spec cũ: unordered.
Equality: SameValueZeroNaN === NaN (true), +0 === -0 (true). Object so sánh reference.
IterableCó thể dùng for...of, spread [...set], Array.from(set).

ES6 Set API

const set = new Set([1, 2, 3]);
set.add(4);        // Thêm
set.delete(2);     // Xóa
set.has(3);        // true
set.clear();       // Xóa hết
set.size;          // 3
for (const v of set) { ... } // Duyệt
[...set];          // Chuyển array

So sánh Set vs Array vs Map

Đặc điểmSetArrayMap
Key-ValueKhông (chỉ value)Không (index → value)Có (key → value)
UniqueCóKhôngKey unique
OrderInsertion orderIndex orderInsertion order
has()O(1)O(n) includes()O(1) has(key)
JSON serializeCần Array.from()NativeCần custom

Ứng dụng thực tế

  • Tag/Category unique list.
  • Visitor tracking (unique IP/user ID).
  • Permission/Role set.
  • Graph algorithms (visited nodes).
  • Dedupe array: const unique = [...new Set(arr)].