Is the return in forEach valid? How to gracefully break a forEach loop?

In JavaScript, forEachis a commonly used array traversal method. However, many people may misunderstand the role of the statement forEachin return. This article will explain in detail whether the statement forEachin returnis valid and how to gracefully interrupt the forEach loop.

forEachIs the in returneffective?

forEachUsing statements within a loop does returnnot break the loop or terminate the loop prematurely. Unlike other loop control statements (such as for, while), forEachin returnis only used to exit the current loop callback function and does not affect forEachthe continued execution of the entire loop.

How to break forEachthe loop?

If you want to break the loop under certain conditions forEach, there are several ways to do this:

1. Use exception throwing:
You can throw an exception in the loop callback function, and then interrupt the loop when the exception is caught.

// 代码
try {
  array.forEach(item => {
    if (condition) {
      throw new Error('Loop Break');
    }
    // 正常的循环处理
  });
} catch (e) {
  if (e.message !== 'Loop Break') {
    throw e;
  }
}

2. Use for...ofloops:
for...of Loops can be interrupted by breakstatements, but the array needs to be converted into an iterator.

// 代码
const array = [1, 2, 3];
const iterator = array[Symbol.iterator]();

for (const item of iterator) {
  if (condition) {
    break;
  }
  // 正常的循环处理
}

3. Use somethe or everymethod:
some The and everymethod truewill interrupt the loop when encountering a return.

// 代码
const array = [1, 2, 3];
array.some(item => {
  if (condition) {
    return true; // 中断循环
  }
  // 正常的循环处理
});

Sample code:

Here's a sample code that demonstrates how to forEachgracefully break a loop in:

// 代码
const array = [1, 2, 3, 4, 5];
let found = false;

array.forEach(item => {
  if (item === 3) {
    found = true;
    return; // 这里的 return 不会中断 forEach 循环
  }
  console.log(item);
});

if (found) {
  console.log('Item found');
}

Summarize

Although the statements forEachin returnwill not interrupt the entire loop, methods such as exception throwing, for...oflooping, or somemethods can be used everyto achieve the effect of interrupting the loop. When using it, choose the appropriate method according to the scenario to ensure the readability and maintainability of the code.

Guess you like

Origin blog.csdn.net/JaneLittle/article/details/132451891