forEach() 方法将会以插入顺序对 Map 对象中的每一个键值对执行一次参数中提供的回调函数。
语法
myMap.forEach(callback[, thisArg])
参数
-
callback - 必要,每个元素所要执行的函数。
-
thisArg -
可选,
callback执行时其this的值。 -
返回值
概述
forEach 方法将对 Map 中真实存在的每一个元素执行一次参数中提供的回调函数,它不会对任何已经被删除的元素执行调用。然而,它还会对键存在而值为 undefined 的元素执行调用。
callback 函数有三个参数:
value- 元素的值key- 元素的键Map- 当前正在被遍历的对象
如果参数 forEach 带有一个 thisArg 参数,在调用的时候,这个参数将传给 callback 函数作为其 this 的值。否则,函数将默认使用 undefined 传给 callback 函数作为其 this 值。最终,这里的 this 的值将依照 函数观测并确定 this 的相关规则 由 callback 函数最终观察到的值决定。
forEach 函数处理的元素的范围为第一次执行 callback 函数时 Map 对象中的键值对集合。在 Map 对象调用 forEach 之后加入的元素将不会被调用 callback 函数。如果在调用 forEach 之后 Map 对象中的被改变或者删除了,它们传给 callback 函数的值将会变成 forEach 函数访问它们时的值;callback 不会访问其调用其间被删除的元素。
forEach 仅仅是对 Map 对象中的每一个元素执行一遍 callback 函数,然后直接返回 undefined。
示例
打印一个 Map 对象中的元素
下面的代码在一行中打印一个 Map 对象的每一个元素:
function logMapElements(value, key, map) {
console.log("m[" + key + "] = " + value);
}
Map([["foo", 3], ["bar", {}], ["baz", undefined]]).forEach(logMapElements);
// logs:
// "m[foo] = 3"
// "m[bar] = [object Object]"
// "m[baz] = undefined"
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Map.prototype.forEach |
Standard | Initial definition. |
浏览器兼容性
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains.
Find out how you can help!
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 38 | 25.0 (25.0) | 11 | 25 | 7.1 |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | 未实现 | 38 | 25.0 (25.0) | 未实现 | 未实现 | 8 |