Map.prototype.forEach()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Map
实例的 forEach()
方法按插入顺序对该映射中的每个键/值对执行一次提供的函数。
¥The forEach()
method of Map
instances executes a provided function once per each key/value
pair in this map, in insertion order.
Try it
语法
参数
¥Parameters
callbackFn
-
为地图中的每个条目执行的函数。使用以下参数调用该函数:
thisArg
Optional-
执行
callbackFn
时用作this
的值。
返回值
描述
¥Description
forEach
方法对实际存在的映射的每个键执行一次提供的 callback
。对于已删除的键,不会调用它。然而,它是针对存在但具有值 undefined
的值执行的。
¥The forEach
method executes the provided callback
once for each key of the
map which actually exist. It is not invoked for keys which have been deleted.
However, it is executed for values which are present but have the value
undefined
.
callback
使用三个参数调用:
¥callback
is invoked with three arguments:
- 该条目的
value
- 该条目的
key
- 正在遍历的
Map
对象
如果将 thisArg
参数提供给 forEach
,则在调用时该参数将传递给 callback
,用作其 this
值。否则,值 undefined
将被传递用作其 this
值。callback
最终可观测到的 this
值根据 确定函数所见的 this
的常用规则 确定。
¥If a thisArg
parameter is provided to forEach
, it will be passed to
callback
when invoked, for use as its this
value. Otherwise, the value
undefined
will be passed for use as its this
value. The this
value
ultimately observable by callback
is determined according to
the usual rules for determining the this
seen by a function.
每个值都会被访问一次,除非在 forEach
完成之前删除并重新添加该值。对于访问之前删除的值,不会调用 callback
。将访问 forEach
完成之前添加的新值。
¥Each value is visited once, except in the case when it was deleted and re-added
before forEach
has finished. callback
is not invoked for values deleted
before being visited. New values added before forEach
has finished will be
visited.
示例
打印 Map 对象的内容
¥Printing the contents of a Map object
以下代码为 Map
对象中的每个元素记录一行:
¥The following code logs a line for each element in an Map
object:
function logMapElements(value, key, map) {
console.log(`map.get('${key}') = ${value}`);
}
new Map([
["foo", 3],
["bar", {}],
["baz", undefined],
]).forEach(logMapElements);
// Logs:
// "map.get('foo') = 3"
// "map.get('bar') = [object Object]"
// "map.get('baz') = undefined"
规范
Specification |
---|
ECMAScript Language Specification # sec-map.prototype.foreach |
浏览器兼容性
BCD tables only load in the browser