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
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
set Chrome Full support 38 Edge Full support 12 Firefox Full support 13 IE Partial support 11
Notes
Partial support 11
Notes
Notes Returns 'undefined' instead of the 'Map' object.
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.

参见