現象:
下例為一個js的foreach操作,看打印的結果,return是無法中斷foreach處理的。
var testArray = [1, 2, 3, 4, 5]; testArray.forEach(element => { if (element == 3) { return; } console.log(element); });
結果:
1 2 4 5
理解:
foreach就是用來一次遍歷完數組左右元素的,如果有中斷操作可以使用普通的for循環。
MDN上是這么解釋的:
There is no way to stop or break a forEach() loop other than by throwing an exception.
If you need such behavior, the forEach() method is the wrong tool. Early termination may be accomplished with: A simple for loop A for...of / for...in loops Array.prototype.every() Array.prototype.some() Array.prototype.find() Array.prototype.findIndex() Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.