JavaScript - WeakSet has() 方法
JavaScript WeakSet 的 has() 方法用于检查指定元素或对象是否存在于此 WeakSet 中。如果 WeakSet 中存在对象,则返回布尔值 true;否则返回 false;如果值不是对象或非注册符号,则始终返回 false。
JavaScript 中的 WeakSet 是一个只能包含对象和非注册符号的集合。它们不能像其他集合(例如 Set)那样存储任何类型的任意值。
语法
以下是 JavaScript 字符串 has() 方法的语法 -
has(value)
参数
此方法接受一个名为"value"的参数,如下所述 -
value - 需要检查该值是否存在于此 WeakSet 中。
返回值
如果该值存在于此 WeakSet 中,则此方法返回"true";否则返回 'false'。
示例
示例 1
如果此 WeakSet 中存在指定的值,则此方法将返回 'true'。
在下面的示例中,我们使用 JavaScript WeakSet 的 has() 方法检查对象 'newObj = {}' 是否存在于此 WeakSet 中。
<html>
<head>
<title>JavaScript WeakSet has() Method</title>
</head>
<body>
<script>
const Obj = new WeakSet();
const newObj = {};
document.write("Appending object to this WeakSet");
Obj.add(newObj);
let res = Obj.has(newObj);
document.write("<br>Does object ", newObj, ' is exists in this WeakSet? ', res);
</script>
</body>
</html>
输出
上述程序返回以下语句 -
Appending object to this WeakSet Does object [object Object] is exists in this WeakSet? true
示例 2
如果指定的值不存在于此 WeakSet 中,此方法将返回 'false'。
以下是 JavaScript WeakSet has() 方法的另一个示例。在此示例中,我们使用此方法检查值 10(它不是对象)是否存在于此 WeakSet 中。
<html>
<head>
<title>JavaScript WeakSet has() Method</title>
</head>
<body>
<script>
const Obj = new WeakSet();
const num = 10;
document.write("Value: ", num);
try {
Obj.add(num);
} catch (error) {
document.write("<br>", error);
}
document.write("<br>Does value ", num, " is exists in this WeakSet? ", Obj.has(num));
</script>
</body>
</html>
输出
Value: 10 TypeError: Invalid value used in weak set Does value 10 is exists in this WeakSet? false

