set() 方法为 Map 对象添加或更新一个指定了键(key)和值(value)的(新)键值对。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
语法
myMap.set(key, value);
参数
- key
-
要添加至相应
Map对象的元素的键。 - value
-
要添加至相应
Map对象的元素的值。
返回值
Map 对象
示例
使用 set 方法
var myMap = new Map();
// 将一个新元素添加到 Map 对象
myMap.set("bar", "foo");
myMap.set(1, "foobar");
// 在Map对象中更新某个元素的值
myMap.set("bar", "baz");
链式使用 set 方法
因为 Set() 方法返回 Map 对象本身,所以你可以像下面这样链式调用它:
// Add new elements to the map with chaining.
myMap.set('bar', 'foo')
.set(1, 'foobar')
.set(2, 'baz');
规范
| 规范 | 状态 | 备注 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Map.prototype.set |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) Map.prototype.set |
Draft |
浏览器兼容性
这个页面上的浏览器兼容性表格是基于结构化数据生成的。如果您想贡献数据,请查看https://github.com/mdn/browser-compat-data并向我们发送请求。
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
set |
Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Partial support 11
|
Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs Full support Yes |
Legend
- Full support
- Full support
- Partial support
- Partial support
- See implementation notes.
- See implementation notes.