此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Set.prototype.has()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
Set 实例的has() 方法返回一个布尔值来指示对应的值是否存在于该集合中。
In this article
尝试一下
const set1 = new Set([1, 2, 3, 4, 5]);console.log(set1.has(1));// Expected output: trueconsole.log(set1.has(5));// Expected output: trueconsole.log(set1.has(6));// Expected output: false语法
js
has(value)参数
value要测试是否存在于
Set对象中的值。
返回值
如果Set 对象中存在具有指定值的元素,则返回true;否则返回false。
示例
>使用 has() 方法
js
const mySet = new Set();mySet.add("foo");console.log(mySet.has("foo")); // trueconsole.log(mySet.has("bar")); // falseconst set1 = new Set();const obj1 = { key1: 1 };set1.add(obj1);console.log(set1.has(obj1)); // trueconsole.log(set1.has({ key1: 1 })); // false, 因为它们是不同的对象引用console.log(set1.add({ key1: 1 })); // 现在 set1 包含 2 个条目规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-set.prototype.has> |