JavaScript - Set.has() 方法
JavaScript 中的 Set.has() 方法用于验证集合中是否存在特定元素。它返回一个布尔值,指示指定元素是否存在于集合中。
语法
以下是 JavaScript Set.has() 方法的语法 -
has(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>
由于元素"Kiwi"存在于集合中,因此返回"false"。
示例 3
在此示例中,我们检查元素"Tutorialspoint"是否存在于空集合中 -
<html>
<body>
<script>
const mySet = new Set();
const result = mySet.has('Tutorialspoint');
document.write(result);
</script>
</body>
</html>
如果我们执行上述程序,它将返回"false"作为结果。

