此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Map.prototype.clear()

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月⁩.

Map 实例的 clear() 方法会移除该 map 中的所有元素。

尝试一下

const map1 = new Map();

map1.set("bar", "baz");
map1.set(1, "foo");

console.log(map1.size);
// Expected output: 2

map1.clear();

console.log(map1.size);
// Expected output: 0

语法

js
clear()

参数

无。

返回值

无(undefined)。

示例

使用 clear()

js
const myMap = new Map();
myMap.set("bar", "baz");
myMap.set(1, "foo");

console.log(myMap.size); // 2
console.log(myMap.has("bar")); // true

myMap.clear();

console.log(myMap.size); // 0
console.log(myMap.has("bar")); // false

规范

Specification
ECMAScript® 2026 Language Specification
# sec-map.prototype.clear

浏览器兼容性

参见