Set.prototype.forEach只接收当前值一个参数,按插入顺序遍历,不支持索引和中断,可选thisArg绑定上下文,与Map.forEach不同,仅专注值本身。

Set.prototype.forEach 方法用于遍历 Set 对象中的每个值,语法和使用方式与 Array.prototype.forEach 类似,但注意:Set 中的回调函数只接收一个参数(当前值),没有索引和原集合参数(因为 Set 没有“索引”概念,且元素唯一、无序)。
基本用法:传入回调函数即可
回调函数会为 Set 中的每个唯一值执行一次,按插入顺序遍历(不是数值或字典序,而是添加时的顺序)。
- 回调函数形参只有一个:
value(当前元素) - 第二个参数
thisArg可选,用于指定回调函数内部this的指向 - 不支持中断(不能用
break或return false提前退出)
示例:简单遍历并打印元素
```js
const mySet = new Set(['apple', 'banana', 'cherry']);
mySet.forEach(value => {
console.log(value);
});
// 输出:
// apple
// banana
// cherry
```
使用 thisArg 绑定上下文
当回调需要访问外部对象的属性或方法时,可传入 thisArg:
立即学习“Java免费学习笔记(深入)”;
- ```js
const obj = { prefix: '[SET]' };
const colors = new Set(['red', 'green']);
colors.forEach(function(value) {
console.log(this.prefix + value);
}, obj); // 第二个参数是 thisArg
// 输出:
// [SET]red
// [SET]green
```
注意:没有索引,也不提供键名
不同于 Map 的 forEach(接收 value, key, map),Set 的 forEach 回调只传 value。如果你需要位置信息,应改用 for...of 配合计数器,或转为数组:
- ```js
let i = 0;
mySet.forEach(value => {
console.log(i++, value);
});
``` - 或:
```js
[...mySet].forEach((value, index) => {
console.log(index, value);
});
```
与 for...of 循环的区别
forEach 是声明式、不可中断、无返回值;for...of 更灵活,支持 break、continue 和 return,也更直观:
- ```js
for (const item of mySet) {
if (item === 'banana') break;
console.log(item);
}
```
不复杂但容易忽略:Set 的 forEach 不传索引,也不传“键”,只专注值本身——这是由 Set 的语义决定的:它只关心“是否存在”,不维护键值对或位置关系。


















