JavaScript - Map.has() 方法



JavaScript 中的Map.has() 方法用於驗證 Map 物件中是否存在具有指定鍵的元素。

此方法接受元素的“鍵”作為引數,以測試其在 Map 物件中的存在性,並返回布林值作為結果。如果 Map 中存在指定的鍵,則返回“true”。否則,返回“false”。

如果 Map 中存在鍵,並且鍵值對中的對應值為“undefined”,Map.has() 方法仍將返回“true”。

語法

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

has(key)

引數

此方法只接受一個引數。具體描述如下:

  • key − 要檢查其在 Map 中是否存在性的鍵。

返回值

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

示例

示例 1

在下面的示例中,我們正在檢查 Map 中是否存在具有指定鍵 ('a') 的元素:

<html>
<body>
   <script>
      let map = new Map();
      map.set('a', 'apple');
      map.set('b', 'banana');
      
      document.write(map.has('a')); // Output: true
   </script>
</body>
</html>

上述程式返回“true”,因為鍵“a”存在於 Map 中。

示例 2

在這裡,我們嘗試檢查 Map 物件中不存在的指定鍵 'b' 的元素。

<html>
<body>
   <script>
      let map = new Map();
      map.set('a', 'apple');
      map.set('b', 'banana');
      
      document.write(map.has('b')); // Output: false
   </script>
</body>
</html>

上述程式返回“false”,因為鍵“b”不存在於 Map 中。

示例 3

在這種情況下,map 具有鍵 'a',其值為 undefined:

<html>
<body>
   <script>
      let map = new Map();
      map.set('a', undefined);
      map.set('b', 'banana');
      
      document.write(map.has('a'));
   </script>
</body>
</html>

上述程式返回 true,因為 'a' 存在,即使其值為 undefined。

廣告