JavaScript - WeakSet has() 方法



JavaScript WeakSet 的has() 方法用於檢查指定元素或物件是否存在於此 WeakSet 中。如果物件存在於此 WeakSet 中,則返回布林值“true”,否則返回“false”,並且如果值不是物件或不是未註冊的符號,則始終返回 false。

JavaScript 中的 WeakSet 是一個集合,它只能包含物件和未註冊的符號。它們不能像其他集合(如 Set)那樣儲存任何型別的任意值。

語法

以下是 JavaScript 字串has() 方法的語法 -

has(value)

引數

此方法接受一個名為“value”的引數,如下所述 -

  • value - 需要檢查在此 WeakSet 中是否存在的值。

返回值

如果該值存在於此 WeakSet 中,則此方法返回“true”;否則返回“false”。

示例

示例 1

如果指定的值存在於此 WeakSet 中,則此方法將返回“true”

在以下示例中,我們使用 JavaScript WeakSet 的has() 方法來檢查物件“newObj = {}”是否存在於此 WeakSet 中。

<html>
<head>
   <title>JavaScript WeakSet has() Method</title>
</head>
<body>
   <script>
      const Obj = new WeakSet();
      const newObj = {};
      document.write("Appending object to this WeakSet");
      Obj.add(newObj);
      let res = Obj.has(newObj);
      document.write("<br>Does object ", newObj, ' is exists in this WeakSet? ', res);  
   </script>    
</body>
</html>

輸出

以上程式返回以下語句 -

Appending object to this WeakSet
Does object [object Object] is exists in this WeakSet? true

示例 2

如果指定的值不存在於此 WeakSet 中,則此方法將返回“false”

以下是 JavaScript WeakeSet has() 方法的另一個示例。在此示例中,我們使用此方法來檢查值10(它不是物件)是否存在於此 WeakSet 中。

<html>
<head>
   <title>JavaScript WeakSet has() Method</title>
</head>
<body>
   <script>
      const Obj = new WeakSet();
      const num = 10;
      document.write("Value: ", num);
      try {
         Obj.add(num);
      } catch (error) {
         document.write("<br>", error);
      }
      document.write("<br>Does value ", num, " is exists in this WeakSet? ", Obj.has(num));  
   </script>    
</body>
</html>

輸出

Value: 10
TypeError: Invalid value used in weak set
Does value 10 is exists in this WeakSet? false
廣告