Iterator.prototype.forEach()
Baseline 2025Newly 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
-
为迭代器生成的每个元素执行的函数。它的返回值会被丢弃。该函数被调用时将传入以下参数:
返回值
描述
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 |