⭐
A: In javascript, the forEach method of an array cannot be interrupted in the normal way. It can only be interrupted by a try catch.
-
ForEach does not support break and continue, only return.
-
Using a return in forEach is equivalent to a continue in a for loop.
const arr = [1.2.3]
arr.forEach(item= > {
if (item === 2) {
return false // Equivalent to the continue in the for loop
} else {
console.log(item)
}
})
/ / 1
/ / 3
Copy the code
ForEach uses break to report an error.
// Interrupt by throwing an exception
const arr = [1.2.3]
try {
arr.forEach(item= > {
if (item === 2) {
throw new Error('jump out forEach')}else {
console.log(item)
}
})
} catch (err) {
console.log(err)
}
Copy the code
Don’t use forEach to break, use a for loop and break.
At the end
If my article is helpful to you, your 👍 is my biggest support ^_^
I’m Allyn, export insight technology, goodbye!
The last:
“Front-end Daily Question (13)” describes some uses of the Array Reduce method
Next up:
What are the common methods of “Front-end Daily Ask (15)” JavaScript strings?