試一試
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 |
瀏覽器相容性
載入中…