WeakMap.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 July 2015.

WeakMap 实例的 has() 返回一个布尔值,指示该 WeakMap 中是否存在具有指定键的元素。

尝试一下

const weakmap1 = new WeakMap();
const object1 = {};
const object2 = {};

weakmap1.set(object1, "foo");

console.log(weakmap1.has(object1));
// Expected output: true

console.log(weakmap1.has(object2));
// Expected output: false

语法

js
has(key)

参数

key

要测试是否在该 WeakMap 对象中存在的元素的键。

返回值

如果指定键的元素存在于 WeakMap 对象中,则返回 true;否则返回 false。如果 key 不是对象或非全局注册的符号,则始终返回 false

示例

使用 has 方法

js
const wm = new WeakMap();
wm.set(window, "foo");

wm.has(window); // 返回 true
wm.has("baz"); // 返回 false

规范

Specification
ECMAScript® 2025 Language Specification
# sec-weakmap.prototype.has

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
has

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
See implementation notes.

参见