Set.prototype.delete()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Set 例項的 delete() 方法會從該集合中移除指定的元素(如果該元素存在於集合中)。

試一試

const set = new Set();
set.add({ x: 10, y: 20 }).add({ x: 20, y: 30 });

// Delete any point with `x > 10`.
set.forEach((point) => {
  if (point.x > 10) {
    set.delete(point);
  }
});

console.log(set.size);
// Expected output: 1

語法

js
setInstance.delete(value)

引數

value

要從 Set 物件中移除的值。物件透過引用比較,而不是按值比較。

返回值

如果 Set 物件中的某個值已被成功移除,則返回 true。如果未在 Set 中找到該值,則返回 false

示例

使用 delete()

js
const mySet = new Set();
mySet.add("foo");

console.log(mySet.delete("bar")); // false; no "bar" element found to be deleted.
console.log(mySet.delete("foo")); // true; successfully removed.

console.log(mySet.has("foo")); // false; the "foo" element is no longer present.

從集合中刪除物件

由於物件是按引用比較的,如果你沒有原始物件的引用,你需要透過檢查單個屬性來刪除它們。

js
const setObj = new Set(); // Create a new set.

setObj.add({ x: 10, y: 20 }); // Add object in the set.

setObj.add({ x: 20, y: 30 }); // Add object in the set.

// Delete any point with `x > 10`.
setObj.forEach((point) => {
  if (point.x > 10) {
    setObj.delete(point);
  }
});

規範

規範
ECMAScript® 2026 語言規範
# sec-set.prototype.delete

瀏覽器相容性

另見