试一试
const map = new Map();
map.set("bar", "foo");
console.log(map.get("bar"));
// Expected output: "foo"
console.log(map.get("baz"));
// Expected output: undefined
语法
js
set(key, value)
参数
返回值
Map 对象。
示例
使用 set()
js
const myMap = new Map();
// Add new elements to the map
myMap.set("bar", "foo");
myMap.set(1, "foobar");
// Update an element in the map
myMap.set("bar", "baz");
链式使用 set() 方法
由于 set() 方法会返回同一个 Map 对象,因此您可以像下面这样链式调用该方法。
js
// Add new elements to the map with chaining.
myMap.set("bar", "foo").set(1, "foobar").set(2, "baz");
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-map.prototype.set |
浏览器兼容性
加载中…