跳出循环的遍历
最编程
2024-03-05 10:25:39
...
- map不能跳出循环,
- forEach跳出本次循环
使用return终止本次循环,执行下一次循环
let arr = [1, 2, 3];
arr.forEach((item, index) => {
if(item === 2) {
console.log('中止本次循环,继续执行下一次循环')
return false;
}
console.log(index)
})
console.log('结束')
- forEach终止循环
因为forEach无法通过正常流程结束循环,可以通过抛出异常的方式实现终止循环
let arr = [1, 2, 3];
try {
arr.forEach((item, index) => {
if(item === 2) {
throw new Error('End')
}
console.log(index)
})
} catch(e) {
if(e.message === 'End') throw e;
}
下表是JS中常用的实现循环遍历的方法的跳出/结束遍历的办法:
方法 | break | continue | return/return false | return true |
---|---|---|---|---|
for | 结束循环 | 跳出本次循环 | 不合法 | 不合法 |
forEach | 不合法 | 不合法 | 跳出本次循环 | 跳出本次循环 |
for...in | 结束循环 | 跳出本次循环 | 不合法 | 不合法 |
Array.map() | 不合法 | 不合法 | 跳出本次循环 | 跳出本次循环 |
Array.some() | 不合法 | 不合法 | 跳出本次循环 | 结束循序 |
Array.every() | 不合法 | 不合法 | 结束循环 | 跳出本次循环 |
Array.filter() | 不合法 | 不合法 | 跳出本次循环 | 跳出本次循环 |
参考链接
JS中如何跳出循环/结束遍历
推荐阅读
-
第 4 章:c 语言中的循环结构
-
解决 Spring Integrated Shiro 集成 CAS 单点登录成功后重定向循环问题的方案
-
MFC 的 TreeCtrl 遍历所有节点
-
文献更新:早期肺癌诊断 - 早期肺癌诊断:基于深度学习的循环外泌体光谱分析
-
python数据分析中pandas对某列Series调用有道翻译API进行翻译--思路:因为翻译接口有访问次数限制,所以先将Series去重,然后调用有道翻译接口将Series中的每个数据,翻译成中文保存为json文件{原始数据:翻译数据},然后对原始Series进行遍历替换
-
遍历控制器中的实例并将其传递给上下文
-
循环遍历线程池和 CompletableFuture 的简单使用
-
41.二叉树 - 二叉树的分层遍历
-
二叉树的分层遍历
-
Unity UI 循环序列图的实现