如何在 JavaScript 中停止 forEach() 方法?
在 JavaScript 中,程序员可以使用 forEach() 方法 迭代数组元素。我们可以调用一个 回调函数,将其作为 forEach() 方法的参数,用于处理每个数组元素。
有时,我们可能需要在为某些元素执行回调函数后停止 forEach() 循环。我们可以使用 'break' 关键字与普通循环一起停止它,如下所示。
for(let i = 0; i < length; i++){
// code
if( some condition ){
break;
}
}
但是我们不能在 forEach() 方法中使用 'break' 关键字。
array.forEach(element => {
// code
if( some condition ){
break;
}
});
上述代码不会停止 forEach() 循环的执行。
本教程将讲解停止 JavaScript 中 forEach() 循环的各种方法。
使用 return 关键字
return 关键字会停止代码的执行。在 forEach() 循环中,它起着 continue 语句的作用。
语法
用户可以按照以下语法使用 return 关键字停止 forEach() 方法的执行。
array.forEach(function (element, index) {
if (condition) {
return;
}
});
在上述语法中,如果条件为真,则不会为该元素执行回调函数的代码。
示例 1
在下面的示例中,我们使用 forEach() 方法处理字符串数组。我们为每个元素调用回调函数,该函数打印每个元素。我们使用了这样一个条件:如果索引 > 2,则从回调函数返回。因此,它不会打印该元素。
<html>
<body>
<h2>Using the <i>return keyword</i> to stop the execution of the forEach() loop.</h2>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
let array = ["string1", "string2", 10, 20, false, true];
function callback(element, index) {
// stop execution of for-loop
if (index > 2) {
return; // works like a continue statement
}
output.innerHTML += "The array element is " + element + "<br/>";
}
array.forEach(callback);
</script>
</body>
</html>
‘return’ 关键字不会中断 forEach() 方法,但如果条件为真,它会起 continue 关键字的作用。
通过抛出异常来停止 forEach() 循环
停止 forEach() 循环的另一种方法是使用 try-catch 语句。当我们想要停止 forEach() 方法的执行时,可以抛出错误。此外,我们可以在 'catch' 块中捕获错误。我们可以在 'finally' 块中执行 forEach() 方法之后需要执行的任何代码。
语法
用户可以按照以下语法使用 try-catch 语句停止 forEach() 方法。
try {
array.forEach((ele) => {
if (condition) {
throw new Error("Break the loop.")
}
})
} catch (error) {
}
在上述语法中,我们使用了 throw 关键字来抛出异常并中断 forEach() 方法。
示例 2
在下面的示例中,我们使用了带有 try-catch 语句的 forEach() 方法。在 forEach() 方法的回调函数中,我们检查元素类型,如果我们发现任何类型为“number”的元素,我们就会抛出错误。
因此,它将停止 forEach() 方法的执行。
<html>
<body>
<h2>Using the <i>try-catch statement</i> to stop the execution of the forEach() loop.</h2>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
let array = ["Cpp", "c", "Java", "JavaScript", 06, true, 43, false];
try {
array.forEach((ele) => {
if (typeof ele == "number") {
throw new Error("Break the loop.")
}
output.innerHTML += "Element value is " + ele + "<br/>";
})
} catch (error) {
output.innerHTML += "Exception thrown from the forEach loop. " + error;
}
</script>
</body>
</html>
在上面的输出中,用户可以观察到,在数组中找到 number 类型元素后,它停止了打印元素。
使用带 break 关键字的普通 for 循环
停止 forEach() 方法执行的最佳解决方案是用普通的 for 循环替换 forEach() 循环,并使用 break 关键字来停止其执行。
语法
用户可以按照以下语法使用带 break 关键字的 for 循环。
for ( ){
if (condition) {
break;
}
}
在上述语法中,当特定条件为真时,我们使用 break 关键字停止 for 循环的执行。
示例 3
在下面的示例中,我们定义了各种值的数组。我们使用普通的 for 循环迭代数组,如果数组值大于 30,我们使用 break 关键字停止 for 循环的执行。
<html>
<body>
<h2>Using the normal for-loop with break keyword to stop the execution of for-loop. </h2>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
let arrayElements = [10, 20, 30, 40, 50, 60, 70, 80, 90];
output.innerHTML += "Some array elements are "
for (let k = 0; k < arrayElements.length; k++) {
if (arrayElements[k] > 30) {
break;
}
output.innerHTML += arrayElements[k] + " , ";
}
</script>
</body>
</html>
方法。第一种方法不会中断循环,而是会作为 'continue' 语句工作。第二种方法使用 try-catch 语句来中断 forEach() 方法。我们不能仅仅为了中断 forEach() 循环而在实际开发中抛出错误。因此,不建议使用第一种和第二种方法。
在第三种方法中,我们用普通的 for 循环替换了 forEach() 方法,并使用了 break 关键字。第三种方法可以正常工作,但是普通的 for 循环 迭代元素的速度可能比 forEach() 方法慢。因此,用户也可以尝试使用 array.some() 和 array.each() 方法 来提高性能。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP