JavaScript - Map.has() 方法
JavaScript 中的 Map.has() 方法用于验证 Map 对象中是否存在具有指定键的元素。
此方法以元素的 "key" 作为参数,测试该元素是否存在于 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"存在,尽管它的值未定义。

