JavaScript 如何停止forEach()方法
停止forEach()循环似乎几乎是一项不可能的任务,但是有一些技巧可以实现。
使用forEach()的示例:
var sum = 0;
var number = [90, 4, 22, 48];
number.forEach(myFunction);
function myFunction(item) {
sum += item;
}
console.log(sum);
方法1
以下方法演示了使用 try-catch 块的方法。以下代码演示了在forEach循环中将事物包围在 try-catch 块中,并在循环中断时抛出异常。
示例: 这个示例使用了上述方法。
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");
}
输出:
pig
lion
Loop has ended
方法2
此方法实际上不会跳出 forEach() 循环,而是将其视为针对所有其他元素的连续语句,即在满足给定条件的元素之后跳过所有其他元素。
示例: 此示例显示了上述方法的使用。
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
极客教程