此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Iterator.prototype.forEach()

Baseline 2025
Newly available

Since March 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

实验性: 这是一项实验性技术
在将其用于生产之前,请仔细检查浏览器兼容性表格

Iterator 实例的 forEach() 方法与 Array.prototype.forEach() 类似:它对迭代器生成的每个元素执行一次提供的函数。

语法

js
forEach(callbackFn)

参数

callbackFn

为迭代器生成的每个元素执行的函数。它的返回值会被丢弃。该函数被调用时将传入以下参数:

element

当前正在处理的元素。

index

当前正在处理的元素的索引。

返回值

undefined

描述

forEach() 迭代该迭代器,并对每个元素调用一次 callbackFn 函数。与大多数其他迭代器帮助方法不同,forEach() 不能很好地处理无限迭代器,因为它不是惰性的。

示例

使用 forEach()

js
new Set([1, 2, 3]).values().forEach((v) => console.log(v));

// 输出:
// 1
// 2
// 3

等价于:

js
for (const v of new Set([1, 2, 3]).values()) {
  console.log(v);
}

规范

Specification
ECMAScript® 2026 Language Specification
# sec-iterator.prototype.foreach

浏览器兼容性

参见