Как остановить метод forEach () в JavaScript?

Опубликовано: 1 Декабря, 2021

Остановка цикла forEach () кажется почти невыполнимой задачей, но вот несколько приемов, с помощью которых мы можем это сделать.

Пример использования forEach ():

var sum = 0;
var number = [90, 4, 22, 48];
number.forEach (myFunction);

function myFunction (item) {
    сумма + = элемент;
}
console.log (сумма);

Уловки для остановки цикла forEach ():

Метод 1. Следующий метод демонстрирует использование блока try-catch. Следующий код демонстрирует окружение объекта блоком try-catch и выдачу исключения при разрыве цикла forEach.

Пример:

Javascript

var animals=["pig", "lion", "boar", "rabbit"];
  
try {
    animals.forEach(myFunction);
  
    function myFunction(item) {
  
        // Condition for breaking the loop
        if(item.localeCompare("boar") == 0) 
  
        /* skips rest of the statements in the
        function and goes to the catch block */
        throw new Exception("Time to end the loop"); 
        console.log(item);
    }
}
catch(e) {
    console.log("Loop has ended");
}

Выход:

свинья
лев
Цикл закончился

Метод 2: Этот метод на самом деле не прерывает цикл forEach (), но считает его непрерывным оператором для всех других элементов, т.е. он пропускает все остальные элементы после элемента, который удовлетворяет заданному условию.

Javascript

var ary = [90, 87, 45, 99];
ary.forEach( function loop(item) {
// This statement acts like a continue
// statement for the remaining elements
// when the condition is satisfied
if (loop.stop){ return ;}
// Prints the element to the console
console.log(item);
// This statement acts like a condition
// and prevents the execution of the
// loop for the remaining elements
if (item == 87) {
loop.stop = true ;
}
});
 Выход:
90
87