📜  JavaScript 中 Set.clear() 和 Set.delete() 方法的区别

📅  最后修改于: 2022-05-13 01:56:15.859000             🧑  作者: Mango

JavaScript 中 Set.clear() 和 Set.delete() 方法的区别

Set.clear()Set.delete()方法都通过删除元素来修改当前 Set。但这两者之间存在一些根本区别,本文将对此进行讨论。

Set.clear() 方法在这个 方法,集合中的所有元素都被删除。因此,结果,集合变为空,集合的大小变为 0。

句法:

Myset.clear()

示例:在此示例中,我们将实现clear()方法。

Javascript


Javascript


输出:

3
2
0

Set.delete() 方法在该方法中,将一个值作为参数。如果 Set 持有该值,则该元素将被删除并返回 true。如果集合中不存在这样的元素,则不会删除任何内容,并且该函数将返回 false。其余元素将不受影响。因此,换句话说, delete()方法删除具有给定值的元素,如果它存在于集合中,并确认它在集合中的可用性。

句法:

Myset.delete(Value)

示例:在此示例中,我们将实现delete()方法。

Javascript


输出:

3
2

set.clear() 和 set.delete() 方法的区别:

   Base of differenceset.clear() methodset.delete() method
Modification in Setclear() method removes all elements from the Set.delete() method removes a certain element(s) from the Set depending upon its availability.
Argumentsclear() method is called without passing anything as an argument.The value of the element intended to be deleted must be passed to an argument to the delete() method.
Return typeclear() method returns “undefined”.elementsdelete() method returns the availability of the given element in the Set. If the element intended to get deleted does not exist in the Set. It returns false otherwise returns true.
Usageclear() method is used to clear out all elements from the set.delete() method is used to delete certain element(s) from the set. As it confirms the availability of the element by returning a Boolean value. It can also be used to check whether the element exists in the set or not.