Map.prototype.set()

set() 方法为 Map 对象添加或更新一个指定了键(key)和值(value)的(新)键值对。

语法

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

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
setChrome Full support 38Edge Full support 12Firefox Full support 13IE Partial support 11
Notes
Partial support 11
Notes
Notes Returns 'undefined' instead of the 'Map' object.
Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support 3.0nodejs Full support Yes

Legend

Full support  
Full support
Partial support  
Partial support
See implementation notes.
See implementation notes.

参见