The forEach loop in the array will report an error if you want to exit the whole loop using break, and return will not jump out of the loop. In other words, the forEach traversal cannot be terminated.
Solution:
Iterate through for to achieve
let arr = ['1', '2', '3', '4', '5'];
for(let i=0; i<arr.length; i++) {
if(arr[i] == '3') break;
console.log(arr[i]) // 1 2
}
Implemented by try--catch throwing exceptions
let arr = ['1', '2', '3', '4', '5'];
try {
arr.forEach((item, index) => {
if (item === '3') {
throw new Error('End')
}
console.log(item) // 1 2
})
} catch (e) {
if (e.message === 'End') throw e;
}
Implemented via reduce iteration, with an interrupt flag set
let arr = ['1', '2', '3', '4', '5'];
arr.reduce(function (p, c) {
if (c == '3') {
this.break = true
}
if (this.break) {
return
}
console.log(c) // 1 2
}, '')
Read More:
- How to Solve Vue & Django Cross-domain Issue
- How to Solve Altium designer Rule Check Without an Error Issue
- How to Solve Hmaster hangs up issue due to namenode switching in Ha mode
- [Solved] Shell loop execute error: syntax error: bad for loop variable
- After SpringBoot starts, exit the console directly and display Process finished with exit code 1
- Vue: How to Solve Error uncaught (in promise) cancel
- How to Solve Error: avoided redundant navigation to current location: “index/user”
- How to Solve Spring Cloud Error context has been closed already
- How to Solve Namedparameterjdbctemplate.queryforobject() Return Error
- How to Solve screenfull plug-in Error (Version Issues)
- Introduce wangeditor5 to run an error: You may need an appropriate loader to handle this file type (es6 compatibility issue)
- How to Solve Error: Unsupported field: HourOfDay
- How to Solve Android Error: gps requires ACCESS_FINE_LOCATION
- How to Solve ES error: “illegal_argument_exception”
- The loop of life and death occurs when the El table component of element UI is bidirectional bound
- How to Solve Logstash error: failed to execute action
- How to Solve DB2 uses Limit Error
- How to Solve Spark Writes Hudi Error
- How to Solve error C2039: “to_ String “: not a member of” STD “