JavaScript - Set.has() 方法



JavaScript 中的 Set.has() 方法用於驗證特定元素是否存在於集合中。它返回一個布林值作為結果,指示指定的元素是否存在於 Set 中。

語法

以下是 JavaScript Set.has() 方法的語法:

has(value)

引數

此方法僅接受一個引數。下面描述了該引數:

  • value − 要在集合中檢查的元素。

返回值

此方法返回一個布林值作為結果。

JavaScript Set.has() 方法示例

以下演示了 Set.has() 方法的基本用法:

示例

示例 1

在以下示例中,我們使用 JavaScript Set.has() 方法搜尋元素“3”是否在此集合中:

<html>
<body>
   <script>
      const mySet = new Set([1, 2, 3, 4, 5]);
      const result = mySet.has(3);
      document.write(result);
   </script>
</body>
</html>

它返回“true”,因為元素“3”存在於集合中。

示例 2

在這裡,我們搜尋一個元素“kiwi”,它不存在於集合中:

<html>
<body>
   <script>
      const mySet = new Set(['Apple', 'Orange', 'Banana']);
      const result = mySet.has('Kiwi');
      document.write(result);
   </script>
</body>
</html>

它返回“false”,因為元素“Kiwi”存在於集合中。

示例 3

在此示例中,我們檢查元素“Tutorialspoint”是否存在於空集合中:

<html>
<body>
   <script>
      const mySet = new Set();
      const result = mySet.has('Tutorialspoint');
      document.write(result);
   </script>
</body>
</html>

如果我們執行上述程式,它將返回“false”作為結果。

廣告