es6 foreach 如何中途退出循環
时间: 2023-02-10 07:49:40 浏览: 76
我们可以使用 `break` 语句来退出循环。
举个例子:
```
const array = [1, 2, 3, 4, 5];
array.forEach((item) => {
if (item === 3) {
break; // 这里的 break 只会中断 forEach 内部的循环,不会中断整个 forEach 方法
}
console.log(item);
});
// Output: 1 2
```
但是,注意 `break` 语句只会中断内部的循环,并不会中断整个 `forEach` 方法,如果想要在 `forEach` 方法中退出循环,我们可以使用一个布尔变量来标记是否需要退出循环,然后在循环内部判断这个变量是否为 `true`,如果是,就在循环内部使用 `return` 语句退出整个 `forEach` 方法。
举个例子:
```
const array = [1, 2, 3, 4, 5];
let shouldBreak = false;
array.forEach((item) => {
if (shouldBreak) {
return; // 这里的 return 会中断整个 forEach 方法
}
if (item === 3) {
shouldBreak = true;
}
console.log(item);
});
// Output: 1 2
```
你也可以使用 `for...of` 循环来替换 `forEach` 方法,并使用 `break` 语句来退出循环。
举个例子:
```
const array = [1, 2, 3, 4, 5];
for (const item of array) {
if (item === 3) {
break;
}
console.log(item);
}
// Output: 1 2
```