目录
使用return关键字
语法
Example 3
示例3
Using the return keyword to stop the execution of the forEach() loop.
通过抛出异常停止forEach()循环
Using the try-catch statement to stop the execution of the forEach() loop.
使用普通的for循环和break关键字
Using the normal for-loop with break keyword to stop the execution of for-loop.
首页 web前端 js教程 如何停止JavaScript中的forEach()方法?

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

Aug 23, 2023 pm 07:53 PM

如何停止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; 
   }
});
登录后复制

在上述语法中,如果条件变为真,则不会执行元素的回调函数的代码。

Example 1

的中文翻译为:

示例1

In the example below, We are using the forEach() method with the array of strings. We call the callback function for every element, which prints every element. We used the condition that if index > 2, it returns from the callback function. So it will not print the element.

<html>
<body>
   <h2 id="Using-the-i-return-keyword-i-to-stop-the-execution-of-the-forEach-loop">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()方法,但如果条件为真,它将作为一个连续关键字起作用。

通过抛出异常停止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) {
}
登录后复制

In the above syntax, we have used the throw keyword to throw the exception and break the forEach() method.

Example 2

的中文翻译为:

示例2

在下面的示例中,我们使用了带有try-catch语句的forEach()方法。在forEach()方法的回调函数中,我们检查元素类型,如果发现任何类型为“number”的元素,就抛出错误。

所以,它将停止执行forEach()方法。

<html>
<body>
   <h2 id="Using-the-i-try-catch-statement-i-to-stop-the-execution-of-the-forEach-loop">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>
登录后复制

In the above output, users can observe that it stops printing the elements after it finds the number type element in the array.

使用普通的for循环和break关键字

停止执行forEach()方法的最佳解决方案是将forEach()循环替换为普通的for循环,并使用break关键字来停止其执行。

语法

Users can follow the syntax below to use the for-loop with the break keyword.

for ( ){
   if (condition) {
      break;
   }
}
登录后复制

在上述语法中,当特定条件成为真时,我们使用 break 关键字停止 for 循环的执行。

Example 3

的中文翻译为:

示例3

在下面的示例中,我们定义了一个包含各种值的数组。我们使用普通的for循环来遍历数组,如果数组的值大于30,我们使用break关键字来停止for循环的执行。

<html>
<body>
   <h2 id="Using-the-normal-for-loop-with-break-keyword-to-stop-the-execution-of-for-loop">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()方法来提高性能。

以上是如何停止JavaScript中的forEach()方法?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何创建和发布自己的JavaScript库? 如何创建和发布自己的JavaScript库? Mar 18, 2025 pm 03:12 PM

文章讨论了创建,发布和维护JavaScript库,专注于计划,开发,测试,文档和促销策略。

如何在浏览器中优化JavaScript代码以进行性能? 如何在浏览器中优化JavaScript代码以进行性能? Mar 18, 2025 pm 03:14 PM

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

前端热敏纸小票打印遇到乱码问题怎么办? 前端热敏纸小票打印遇到乱码问题怎么办? Apr 04, 2025 pm 02:42 PM

前端热敏纸小票打印的常见问题与解决方案在前端开发中,小票打印是一个常见的需求。然而,很多开发者在实...

如何使用浏览器开发人员工具有效调试JavaScript代码? 如何使用浏览器开发人员工具有效调试JavaScript代码? Mar 18, 2025 pm 03:16 PM

本文讨论了使用浏览器开发人员工具的有效JavaScript调试,专注于设置断点,使用控制台和分析性能。

如何使用源地图调试缩小JavaScript代码? 如何使用源地图调试缩小JavaScript代码? Mar 18, 2025 pm 03:17 PM

本文说明了如何使用源地图通过将其映射回原始代码来调试JAVASCRIPT。它讨论了启用源地图,设置断点以及使用Chrome DevTools和WebPack之类的工具。

如何有效地使用Java的收藏框架? 如何有效地使用Java的收藏框架? Mar 13, 2025 pm 12:28 PM

本文探讨了Java收藏框架的有效使用。 它强调根据数据结构,性能需求和线程安全选择适当的收集(列表,设置,地图,队列)。 通过高效优化收集用法

初学者的打字稿,第2部分:基本数据类型 初学者的打字稿,第2部分:基本数据类型 Mar 19, 2025 am 09:10 AM

掌握了入门级TypeScript教程后,您应该能够在支持TypeScript的IDE中编写自己的代码,并将其编译成JavaScript。本教程将深入探讨TypeScript中各种数据类型。 JavaScript拥有七种数据类型:Null、Undefined、Boolean、Number、String、Symbol(ES6引入)和Object。TypeScript在此基础上定义了更多类型,本教程将详细介绍所有这些类型。 Null数据类型 与JavaScript一样,TypeScript中的null

开始使用Chart.js:PIE,DONUT和BUBBLE图表 开始使用Chart.js:PIE,DONUT和BUBBLE图表 Mar 15, 2025 am 09:19 AM

本教程将介绍如何使用 Chart.js 创建饼图、环形图和气泡图。此前,我们已学习了 Chart.js 的四种图表类型:折线图和条形图(教程二),以及雷达图和极地区域图(教程三)。 创建饼图和环形图 饼图和环形图非常适合展示某个整体被划分为不同部分的比例。例如,可以使用饼图展示野生动物园中雄狮、雌狮和幼狮的百分比,或不同候选人在选举中获得的投票百分比。 饼图仅适用于比较单个参数或数据集。需要注意的是,饼图无法绘制值为零的实体,因为饼图中扇形的角度取决于数据点的数值大小。这意味着任何占比为零的实体

See all articles