js 如何让forEach可以break?
While working with Java Script, all of us must have surely run into the case where we need to loop through an array and break the running loop if a certain condition is met. There are many methods how we can loop through an array but we are always looking for the most efficient way to do that.
Our favorite loop method: Array.prototype.forEach
forEach is such an useful method.
But…how can I break the forEach loop?
Well… you can’t break forEach.
1
2
3
4
5
6
|
var arr = [ "Kathmandu" , "Pokhara" , "Lumbini" , "Gorkha" ]; arr.forEach( function (value, index, _arr) { console.log(index + ": " + value); return false ; }); |
The result should look like
1
2
3
4
|
0: Kathmandu 1: Pokhara 2: Lumbini 3: Gorkha |
It’s still iterating through all items in the array. What should I do if I want to stop the loop based on the condition? We either set a variable that changes only if the condition is met, but it will still mean that the loop will iterate until the array is exhausted to the last item.
So, what do we do?? It’s simple.
Don’t use “forEach”. Use “some” or “every”.
Array.prototype.some
Array.prototype.some is pretty much the same as forEach but it break when the callback returns true.
Example:
1
2
3
4
5
6
|
var arr= [ "Kathmandu" , "Pokhara" , "Lumbini" , "Gorkha" ]; arr.some( function (value, index, _arr) { console.log(index + ": " + value); return value === "Pokhara" ; }); |
The result should look like
1
2
|
0: Kathmandu 1: Pokhara |
What happened here? Since the third iteration returned true, we successfully stopped the loop!
Array.prototype.every
Array.prototype.every is almost identical to some except it’s expecting false to break the loop.
Example:
1
2
3
4
5
6
|
var arr = [ "Kathmandu" , "Pokhara" , "Lumbini" , "Gorkha" ]; arr.every( function (value, index, _arr) { console.log(index + ": " + value); return value.indexOf( "Lumbini" ) < 0; }); |
The result should look like
1
2
3
|
0: Kathmandu 1: Pokhara 2: Lumbini |
What happened here? Since the third iteration returned false, we successfully stopped the loop!
Now you can break loops whenever you want! Enjoy.
Source:http://sajanmaharjan.com.np/2016/08/12/javascript-break-foreach/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话