js foreach 不能中斷的現象及理解


現象:

下例為一個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.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM