JavaScript Set và WeakSet

Trong hướng dẫn này, bạn sẽ tìm hiểu về JavaScript Sets và WeakSets với sự trợ giúp của các ví dụ.

JavaScript ES6 đã giới thiệu hai cấu trúc dữ liệu mới, tức là Setvà WeakSet.

Set tương tự như một mảng cho phép chúng ta lưu trữ nhiều mục như số, chuỗi, đối tượng,… Tuy nhiên, không giống như mảng, một tập hợp không thể chứa các giá trị trùng lặp.

Tạo bộ JavaScript

Để tạo một Set, bạn cần sử dụng hàm new Set()tạo. Ví dụ,

// create Set
const set1 = new Set(); // an empty set
console.log(set1); // Set {}

// Set with multiple types of value
const set2 = new Set([1, 'hello', {count : true}]);
console.log(set2); // Set {1, "hello", {count: true}}

Khi các giá trị trùng lặp được chuyển cho một Setđối tượng, các giá trị trùng lặp sẽ bị loại trừ.

// Set with duplicate values
const set3 = new Set([1, 1, 2, 2]);
console.log(set3); // Set {1, 2}

Truy cập các phần tử tập hợp

Bạn có thể truy cập Setcác phần tử bằng values()phương thức và kiểm tra xem có phần tử bên trong Setbằng has()phương thức hay không. Ví dụ,

const set1 = new Set([1, 2, 3]);

// access the elements of a Set
console.log(set1.values()); // Set Iterator [1, 2, 3]

Bạn có thể sử dụng has()phương pháp này để kiểm tra xem phần tử có nằm trong Tập hợp hay không. Ví dụ,

const set1 = new Set([1, 2, 3]);

// check if an element is in Set
console.log(set1.has(1));

Thêm các yếu tố mới

Bạn có thể thêm các phần tử vào một Tập hợp bằng add()phương pháp này. Ví dụ,

const set = new Set([1, 2]);
console.log(set.values());

// adding new elements
set.add(3);
console.log(set.values());

// adding duplicate elements
// does not add to Set
set.add(1);
console.log(set.values());

Đầu ra

Set Iterator [1, 2]
Set Iterator [1, 2, 3]
Set Iterator [1, 2, 3]

Loại bỏ các phần tử

Bạn có thể sử dụng clear()và delete()phương thức để xóa các phần tử khỏi Tập hợp.

Các delete()phương pháp loại bỏ một yếu tố cụ thể từ một Set. Ví dụ,

const set = new Set([1, 2, 3]);
console.log(set.values()); // Set Iterator [1, 2, 3]

// removing a particular element
set.delete(2);
console.log(set.values()); // Set Iterator [1, 3]

Các clear()phương pháp loại bỏ tất cả các yếu tố từ một Set. Ví dụ,

const set = new Set([1, 2, 3]);
console.log(set.values()); // Set Iterator [1, 2, 3]

// remove all elements of Set
set.clear();
console.log(set.values()); // Set Iterator []

Lặp lại các bộ

Bạn có thể lặp qua các phần tử Set bằng cách sử dụng vòng lặp for … of hoặc phương thức forEach () . Các phần tử được truy cập theo thứ tự chèn. Ví dụ,

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

// looping through Set
for (let i of set) {
    console.log(i);
}

Đầu ra

1
2
3

JavaScript WeakSet

WeakSet tương tự như một Set. Tuy nhiên, WeakSet chỉ có thể chứa các đối tượng trong khi một Bộ có thể chứa bất kỳ kiểu dữ liệu nào như chuỗi, số, đối tượng, v.v. Ví dụ:

const weakSet = new WeakSet();
console.log(weakSet); // WeakSet {}

let obj = {
    message: 'Hi',
    sendMessage: true
}

// adding object (element) to WeakSet
weakSet.add(obj);

console.log(weakSet); // WeakSet {{message: "Hi", sendMessage: true}}

Khi bạn cố gắng thêm các kiểu dữ liệu khác ngoài các đối tượng, WeakSet sẽ xuất hiện một lỗi. Ví dụ,

// trying to add string to WeakSet
weakSet.add('hello');

// throws error
// TypeError: Attempted to add a non-object key to a WeakSet
console.log(weakSet);

Phương thức WeakSet

WeakSets có phương pháp add()delete()và has(). Ví dụ,

const weakSet = new WeakSet();
console.log(weakSet); // WeakSet {}

const obj = {a:1};

// add to a weakSet
weakSet.add(obj);
console.log(weakSet); // WeakSet {{a: 1}}

// check if an element is in Set
console.log(weakSet.has(obj)); // true

// delete elements
weakSet.delete(obj);
console.log(weakSet); // WeakSet {}

WeakSets Không thể lặp lại

Không giống như Sets, WeakSets không thể lặp lại. Ví dụ,

const weakSet = new WeakSet({a:1});

// looping through WeakSet
for (let i of weakSet) {

    // TypeError
    console.log(i);
}

Các phép toán tập hợp

Trong JavaScript, Set không cung cấp các phương thức dựng sẵn để thực hiện các phép toán như liên hợp, giao, khác biệt,… Tuy nhiên, chúng ta có thể tạo các chương trình để thực hiện các phép toán đó.

Ví dụ: Đặt Hoạt động Liên minh

// perform union operation
// contain elements of both sets
function union(a, b) {
    let unionSet = new Set(a);
    for (let i of b) {
        unionSet.add(i);
    }
    return unionSet
}

// two sets of fruits
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['grapes', 'apple', 'banana']);

let result = union(setA, setB);

console.log(result);

Đầu ra

Set {"apple", "mango", "orange", "grapes", "banana"}

Ví dụ: Đặt hoạt động giao lộ

// perform intersection operation
// elements of set a that are also in set b
function intersection(setA, setB) {
    let intersectionSet = new Set();

    for (let i of setB) {
        if (setA.has(i)) {
            intersectionSet.add(i);
        }
    }
    return intersectionSet;
}

// two sets of fruits
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['grapes', 'apple', 'banana']);

let result = intersection(setA, setB);

console.log(result);

Đầu ra

Set {"apple"}

Ví dụ: Đặt hoạt động khác biệt

// perform difference operation
// elements of set a that are not in set b
function difference(setA, setB) {
    let differenceSet = new Set(setA)
    for (let i of setB) {
        differenceSet.delete(i)
    }
    return differenceSet
}

// two sets of fruits
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['grapes', 'apple', 'banana']);

let result = difference(setA, setB);

console.log(result);

Đầu ra

Set {"mango", "orange"}

Ví dụ: Đặt hoạt động tập hợp con

// perform subset operation
// true if all elements of set b is in set a
function subset(setA, setB) {
    for (let i of setB) {
        if (!setA.has(i)) {
            return false
        }
    }
    return true
}

// two sets of fruits
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['apple', 'orange']);

let result = subset(setA, setB);

console.log(result);

Đầu ra

true

JavaScript Setsvà WeakSetsđược giới thiệu trong ES6 . Một số trình duyệt có thể không hỗ trợ việc sử dụng chúng. Để tìm hiểu thêm, hãy truy cập hỗ trợ JavaScript Sets và hỗ trợ JavaScript WeakSets .









Gõ tìm kiếm nhanh...