当前位置:网站首页>JS function package foreach use return can not jump out of the outer function
JS function package foreach use return can not jump out of the outer function
2022-04-23 07:03:00 【NOyesNONO_】
stay forEach Use in return It will only jump out of this cycle
let a = 1, b = 1
let c = 2, d = 2
let e = 3, f = 3
let list = [1, 2, 3, 4, 5, 6, 7]
function foo() {
if (a === b) {
list.forEach(item => {
if (item === 3) {
console.log(333333333)
return
}
})
//forEach Medium return Come out here and continue
if (e === f) {
console.log('e === f')
return
}
}
}
Output 333333333 and e === f
Solution 1 , use for Instead of forEach
Solution 2 , use flag Judge , The need to return Where to modify flag Value , Use in affected areas flag Decide whether to execute
function foo() {
let flag = true
if (a === b) {
list.forEach(item => {
if(item === 3){
console.log(333333333)
flag = false
return
}
})
if (e === f && flag) {
console.log('e === f')
return
}
}
}
Only the output 333333333
forEach It's a function itself , Perform the given function once for each element of the array . The array has several elements , Just execute the function several times . therefore forEach Medium return It will only jump out of this circular function , and for Loop is to jump out of all loops
function foo(){
list.forEach(item => {
if(item === 3){
console.log(333333333)
flag = false
return
}
// newly added
console.log(111111)// This will output 6 Time ,List The length is 7, Get rid of item by 3 That time .
})
console.log(' Out of the loop , Within the function ')// perform
}
function foo(){
for (let i = 0; i < list.length; i++) {
if (list[i] === 3) {
console.log(333333333)
return
}
console.log(0) // Only output 2 Time , yes list[i] by 1,2 Two times
}
console.log(' Out of the loop , Within the function ')// Don't execute
}
版权声明
本文为[NOyesNONO_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230601165606.html
边栏推荐
- SSM项目在阿里云部署
- LeetCode刷题|13罗马数字转整数
- 【OSS文件上传快速入门】
- Concurrent optimization request
- Implementation of leetcode question brushing str ()
- 异常记录-13
- 异常记录-22
- Include of ansible module_ Tasks: why is the imported task not executed after adding tags?
- Imitation scallop essay reading page
- 阅读笔记:Meta Matrix Factorization for Federated Rating Predictions
猜你喜欢
随机推荐
LeetCode刷题|两个链表的第一个公共节点
bcc安装和基本工具使用说明
Prometheus的relabel_configs和metric_relabel_configs解释及用法示例
rdma网络介绍
异常记录-15
MySQL索引【数据结构+索引创建原则】
Concurrent optimization request
MySQL 【读写锁+表锁+行锁+MVCC】
DNA reveals surprise ancestry of mysterious Chinese mummies
关于Postgres主从复制延迟监控的错误告警问题
ES入门学习笔记
[no steps in a small step to a thousand miles] Oracle Application derivative ora-01455 error reporting processing
openvswitch 编译安装
LeetCode刷题|368最大整除子集(动态规划)
异常记录-17
[shell script exercise] batch add the newly added disks to the specified VG
Prometheus Thanos快速指南
Redis practice notes and source code analysis
冬季实战营 动手实战-MySQL数据库快速部署实践 领鼠标 云小宝
Oracle net service: listener and service name resolution method