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

瀏覽器相容性

另見