Set.prototype.forEach()

Set 实例的 forEach() 方法按插入顺序对该集合中的每个值执行一次提供的函数。

¥The forEach() method of Set instances executes a provided function once for each value in this set, in insertion order.

Try it

语法

¥Syntax

js
forEach(callbackFn)
forEach(callbackFn, thisArg)

参数

¥Parameters

callback

为集合中的每个条目执行的函数。使用以下参数调用该函数:

value

每次迭代的值。

key

每次迭代的关键。这始终与 value 相同。

set

正在迭代的集合。

thisArg Optional

执行 callbackFn 时用作 this 的值。

返回值

¥Return value

无 (undefined)。

¥None (undefined).

描述

¥Description

forEach() 方法对 Set 对象中实际存在的每个值执行一次提供的 callback。对于已删除的值不会调用它。然而,它是针对存在但具有值 undefined 的值执行的。

¥The forEach() method executes the provided callback once for each value which actually exists in the Set object. It is not invoked for values 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:

  • 元素值
  • 元素键
  • 正在遍历的 Set 对象

然而,Set 对象中没有键,因此前两个参数都是 Set 中包含的值。这是为了使其与 MapArray 的其他 forEach() 方法保持一致。

¥There are no keys in Set objects, however, so the first two arguments are both values contained in the Set. This is to make it consistent with other forEach() methods for Map and Array.

如果将 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.

forEach()Set 对象中的每个元素执行一次 callback 函数;它不返回值。

¥forEach() executes the callback function once for each element in the Set object; it does not return a value.

示例

¥Examples

记录 Set 对象的内容

¥Logging the contents of a Set object

以下代码为 Set 对象中的每个元素记录一行:

¥The following code logs a line for each element in a Set object:

js
function logSetElements(value1, value2, set) {
  console.log(`s[${value1}] = ${value2}`);
}

new Set(["foo", "bar", undefined]).forEach(logSetElements);

// Logs:
// "s[foo] = foo"
// "s[bar] = bar"
// "s[undefined] = undefined"

规范

Specification
ECMAScript Language Specification
# sec-set.prototype.foreach

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看