Set.prototype.has()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Set 实例的 has() 方法返回一个布尔值,表示指定值是否存在于此 Set 中。

试一试

const set = new Set([1, 2, 3, 4, 5]);

console.log(set.has(1));
// Expected output: true

console.log(set.has(5));
// Expected output: true

console.log(set.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")); // true
console.log(mySet.has("bar")); // false

const set = new Set();
const obj = { key1: 1 };
set.add(obj);

console.log(set.has(obj)); // true
console.log(set.has({ key1: 1 })); // false, because they are different object references
console.log(set.add({ key1: 1 })); // now set contains 2 entries

规范

规范
ECMAScript® 2026 语言规范
# sec-set.prototype.has

浏览器兼容性

另见