JavaScript中如何终止forEach循环,跳出双层For循环?

发布时间 2024-01-08 22:33:20作者: jack_Meng

在JavaScript中,forEach方法是用于遍历数组的,通常没有直接终止循环的机制。然而,我们可以使用一些技巧来模拟终止forEach循环。以下是几种常见的方法

1.使用return语句

forEach回调函数内部使用return语句可以实现类似终止循环的效果。当需要终止循环时,可以在回调函数中返回false或者任意其他特定值。

const arr = [1, 2, 3, 4, 5, 6, 7];
let terminate = false;

arr.forEach((element) => {
  if (terminate) {
    return;
  }

  console.log(element);

  if (element === 3) {
    terminate = true; // 终止循环
  }
});

2.使用异常处理:

通过抛出一个自定义的异常,可以终止forEach循环。在捕获到该异常后,程序会跳出forEach循环。

const arr = [1, 2, 3, 4, 5, 6, 7];

try {
  arr.forEach((element) => {
    console.log(element);
  
    if (element === 3) {
      throw 'TerminateException'; // 抛出自定义异常
    }
  });
} catch (e) {
  if (e !== 'TerminateException') {
    throw e; // 抛出其他异常
  }
}

3.使用for...of循环:

如果只需要在特定条件下终止循环,可以考虑使用for...of循环代替forEach循环。for...of循环支持break语句来终止循环。

const arr = [1, 2, 3, 4, 5, 6, 7];

for (const item of arr) {
  console.log(item);
  
  if (item === 4) {
    break; // 终止循环
  }
}

4.将数组长度设置成0

const array = [ 1, 2, 3, 4, 5, 6, 7 ]

array.forEach((item) => {
  if (item >= 4) {
    console.log(item) // 输出:4
    array.length = 0
  }
})

5.建议使用for循环和some方法

const arr = [1, 2, 3, 4, 5, 6, 7]

for (let i = 0, len = arr.length; i < len; i++) {
  if (arr[ i ] >= 4) {
    console.log(arr[ i ]) // 4
    break // return
  }
}

6.双层for循环跳出循环

// 双层for循环跳出循环 =>
for (let index = 0; index < 10; index++) {
    console.log('----?----', '第一个循环');
    let flag = false;
    for (let ind = 0; ind < 10; ind++) {
        console.log('----?----', '第二个循环', index, ind);
        if(index * ind > 20) {
            console.log('----?----', '跳出循环');
            flag = true;
            break;
        }
    }
    if(flag) {
        break
    }
}

outer: for (let index = 0; index < 10; index++) {
    console.log('----?----', '第一个循环');
    for (let ind = 0; ind < 10; ind++) {
        console.log('----?----', '第二个循环', index, ind);
        if(index * ind > 20) {
            console.log('----?----', '跳出循环');
            break outer; // 这个是跳出整个循环
            // return 这个是终止循环
        }
    }
}

 

【出处】:https://www.cnblogs.com/dreamtt/p/17808107.html

=======================================================================================