JavaScript 中的 Set.has() 方法用于验证集合中是否存在特定元素。它返回一个 Boolean 值作为结果,指示指定的元素是否存在于 Set 中。
语法
以下是 JavaScript Set.has() 方法的语法 -
has(value)
参数
此方法只接受一个参数。下面描述相同 -
- value -要在集合中检查的元素。
返回值
此方法返回一个 Boolean 值作为 result。
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
在此示例中,我们将检查元素 “qikepu是否存在于空集中 -
<html>
<body>
<script>
const mySet = new Set();
const result = mySet.has('qikepu');
document.write(result);
</script>
</body>
</html>
如果我们执行上述程序,它会返回 “false” 作为结果。