尝试一下
function logSetElements(value1, value2, set) {
console.log(`s[${value1}] = ${value2}`);
}
new Set(["foo", "bar", undefined]).forEach(logSetElements);
// Expected output: "s[foo] = foo"
// Expected output: "s[bar] = bar"
// Expected output: "s[undefined] = undefined"
语法
js
forEach(callbackFn)
forEach(callbackFn, thisArg)
参数
callback-
为集合中每个元素执行的函数,使用以下参数调用该函数:
thisArg可选-
执行
callbackFn时用作this的值。
返回值
无(undefined)。
描述
forEach() 方法对 Set 对象中实际存在的每个值执行一次提供的 callback。对于已删除的值,不会调用它。但是,它会对存在但值为 undefined 的值执行。
callback 被调用时带有三个参数:
- 元素的值
- 元素的键
- 被遍历的
Set
Set 对象中没有键,所以前两个参数都是 Set 中包含的值。这是为了与 Map 和 Array 的 forEach() 方法保持一致。
如果提供了一个 thisArg 参数给 forEach 函数,则参数将会作为回调函数中的 this值。否则 this 值为 undefined。回调函数中 this 的绑定是根据函数被调用时通用的 this 绑定规则来决定的。
每个值都访问一次,除非在 forEach() 完成之前删除并重新添加它。在访问之前删除的值不会调用 callback。在 forEach() 完成之前添加的新值将被访问。
forEach() 对 Set 对象中的每个元素执行一次 callback 函数;它没有返回值。
示例
>输出集合对象的内容
以下代码依次打印 Set 对象的元素:
js
function logSetElements(value1, value2, set) {
console.log(`s[${value}] = ${value2}`);
}
new Set(["foo", "bar", undefined]).forEach(logSetElements);
// logs:
// "s[foo] = foo"
// "s[bar] = bar"
// "s[undefined] = undefined"
规范
| 规范 |
|---|
| ECMAScript® 2027 Language Specification> # sec-set.prototype.foreach> |