Set.prototype.delete()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Set 实例的 delete() 方法会从此集合中删除指定值(如果该值在集合中)。

¥The delete() method of Set instances removes a specified value from this set, if it is in the set.

Try it

语法

¥Syntax

js
setInstance.delete(value)

参数

¥Parameters

value

要从 Set 中删除的值。

返回值

¥Return value

如果 value 已在 Set 中,则返回 true;否则 false

¥Returns true if value was already in Set; otherwise false.

示例

¥Examples

使用 delete()方法

¥Using the delete() method

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.

从集合中删除对象

¥Deleting an object from a set

由于对象是通过引用进行比较的,因此如果没有对原始对象的引用,则必须通过检查各个属性来删除它们。

¥Because objects are compared by reference, you have to delete them by checking individual properties if you don't have a reference to the original object.

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);
  }
});

规范

Specification
ECMAScript Language Specification
# sec-set.prototype.delete

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看