📜  如何在 JavaScript 中停止 forEach() 方法?

📅  最后修改于: 2022-05-13 01:56:50.602000             🧑  作者: Mango

如何在 JavaScript 中停止 forEach() 方法?

停止forEach()循环似乎几乎是一项不可能完成的任务,但这里有一些我们可以做到的技巧。

使用 forEach() 的示例:

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

function myFunction(item) {
    sum += item;
}
console.log(sum);

停止 forEach() 循环的技巧:

方法一:下面的方法演示了使用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");
}


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; 
    } 
});


输出:

pig
lion
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; 
    } 
});
Output:
90
87