Iterator.prototype.forEach()

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

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

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

语法

js
forEach(callbackFn)

参数

callbackFn

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

element

当前正在处理的元素。

index

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

返回值

描述

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
Iterator Helpers
# sec-iteratorprototype.foreach

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
forEach

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.
Has more compatibility info.

参见