当前位置:网站首页>js 函数包裹forEach中使用return跳不出外层函数
js 函数包裹forEach中使用return跳不出外层函数
2022-04-23 06:02:00 【NOyesNONO_】
在forEach中使用return只会跳出本次循环
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中的return出来到这里继续执行
if (e === f) {
console.log('e === f')
return
}
}
}
输出 333333333 和 e === f
解决方法一,用for代替forEach
解决方法二,用flag判断,在需要return的地方修改flag的值,在受影响的地方用flag决定是否执行
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
}
}
}
只输出 333333333
forEach本身是函数,对数组的每个元素执行一次给定的函数。数组有几个元素,就执行几次函数。所以forEach中的return 只会跳出本次循环函数,而for循环则是跳出全部循环
function foo(){
list.forEach(item => {
if(item === 3){
console.log(333333333)
flag = false
return
}
//新增
console.log(111111)//这里会输出6次,List长度是7,除掉item为3的那次。
})
console.log('循环外,函数内')//执行
}
function foo(){
for (let i = 0; i < list.length; i++) {
if (list[i] === 3) {
console.log(333333333)
return
}
console.log(0) //只会输出2次,是list[i]为1,2的两次
}
console.log('循环外,函数内')//不执行
}
版权声明
本文为[NOyesNONO_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/NOyesNONO_/article/details/120986153
边栏推荐
- Unix期末考试总结--针对直系
- Working principle and practice of browser
- Introduction to common APIs for EBFP programming
- 用Future与CountDownLatch实现多线程执行多个异步任务,任务全部完成后返回结果
- 异常记录-13
- The time format is incorrect, and an error is reported when running the SQL file
- Introduction to DDoS attack / defense
- Each traversal usage of tp6
- MySQL【ACID+隔离级别+ redo log + undo log】
- 基於DPDK實現VPC和IDC間互聯互通的高性能網關
猜你喜欢
随机推荐
Unix期末考试总结--针对直系
ebfp编程常用API介绍
Leak detection and vacancy filling (IV)
Ansible basic commands, roles, built-in variables and tests judgment
Prometheus Cortex多租户读写的实现
异常记录-13
Introduction to DDoS attack / defense
【代码解析(3)】Communication-Efficient Learning of Deep Networks from Decentralized Data
如何使用TiUP部署一个TiDB v5.0集群
Oracle Net Service:监听器与服务名解析方法
Working principle and practice of browser
【OSS文件上传快速入门】
Typescript (lower)
[MySQL basics] startup options, system variables and status variables
SQL学习|基础查询与排列
异常记录-18
The time format is incorrect, and an error is reported when running the SQL file
LeetCode刷题|13罗马数字转整数
Baidu map coordinates, Google coordinates and Tencent coordinates are mutually transformed
Sum (if) in MySQL_ Sum (if ()) in MySQL