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

Kiểm tra giá trị có tồn tại trong JavaScript Set

Dùng Set.prototype.has(value) — trả true nếu có, false nếu không.

Ví dụ

let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1); // duplicate bỏ qua
mySet.add(3);
mySet.add("a");

console.log(mySet);           // Set { 1, 2, 3, 'a' }
console.log(mySet.has(55));   // false
console.log(mySet.has(""));   // false
console.log(mySet.has({}));   // false (object rỗng khác reference)
console.log(mySet.has(1));    // true
console.log(mySet.has("a"));  // true

Phương thức has() độ phức tạp **O(1)** — nhanh hơn Array.includes() (O(n)).