Example of how to exit the loop in Array.forEach in js

Example of how to exit the loop in Array.forEach in js

forEach() Method

Syntax: array.forEach(callback(currentvalue,index,arr),thisValue)

in

callback is a function executed for each element in the array, which can accept 1-3 parameters:

  • The currentvalue parameter represents the current element of the array, a required parameter
  • The index parameter represents the current element index, optional parameter
  • The arr parameter indicates the array to which the current element belongs. It is an optional parameter.

thisValue represents the this point when the callback function callback() is executed. Optional parameter. When not written, the default is to point to the window global

Example

    var arr = [1, 3, 5, 13, 2];
    var res = arr.forEach(function(item,index) {
        console.log(`The ${index+1}th element of the array is ${item}`);
    })
    console.log(res); //The return value of forEach is undefined,

Running results:

How to jump out of the loop in Array.forEach in js

forEach cannot jump out of the loop through break or return. The general way to jump out of the loop is to throw an exception:

 try {
   let array = [1, 2, 3, 4]
   array.forEach((item, index) => {
     if (item === 3) {
       throw new Error('end')//If an error occurs, the loop will be exited} else {
       console.log(item)
     }
   })
 } catch (e) {
 }

This way of writing is actually very troublesome.

Solution:

1. Use every instead:

let array = [1, 2, 3, 4]
array.every((item, index) => {
  if (item === 3) {
    return true
  } else {
    console.log(item)
  }
})

2. Write one yourself 😁

//Array traversal that can jump out of the loop Array.prototype.loop = function(cbk) {
  //Judge whether the current array is empty if (this?.length) {
    for (let i = 0; i < this.length; i++) {
      let stop = cbk(this[i], i, this)
      //Judge whether to stop the loop if (stop) {
        break
      }
    }
  }
}


let array = [1, 2, 3, 4]
array.loop ((item, index) => {
  if (item === 3) {
    return true
  } else {
    console.log(item)
  }
})

Summarize

This is the end of this article about Array.forEach jumping out of the loop in js. For more relevant content about Array.forEach jumping out of the loop in js, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of JavaScript Array.reduce source code
  • JavaScript Array.flat() function usage analysis
  • JavaScript Array.prototype.slice usage instructions
  • JavaScript mapper array.flatMap()

<<:  Vue implements form data validation example code

>>:  Detailed explanation of the principles and usage examples of MySQL join query, union query, and subquery

Recommend

Vue global filter concepts, precautions and basic usage methods

Table of contents 1. The concept of filter 1. Cus...

JavaScript to achieve fireworks effects (object-oriented)

This article shares the specific code for JavaScr...

The benefits of div+css and web standard pages

The div element is used to provide structure and b...

Tomcat Server Getting Started Super Detailed Tutorial

Table of contents 1. Some concepts of Tomcat –1, ...

Style trigger effect of web page input box

<br />This example mainly studies two parame...

ElementUI component el-dropdown (pitfall)

Select and change: click to display the current v...

Linux RabbitMQ cluster construction process diagram

1. Overall steps At the beginning, we introduced ...

WeChat applet implements fixed header and list table components

Table of contents need: Function Points Rendering...

How to deploy LNMP architecture in docker

Environmental requirements: IP hostname 192.168.1...

Detailed explanation of MySQL 5.7.9 shutdown syntax example

mysql-5.7.9 finally provides shutdown syntax: Pre...

JavaScript Composition and Inheritance Explained

Table of contents 1. Introduction 2. Prototype ch...

Logrotate implements Catalina.out log rotation every two hours

1. Introduction to Logrotate tool Logrotate is a ...

Example steps for using AntV X6 with Vue.js

Table of contents 0x0 Introduction 0x1 Installati...

Zabbix monitoring solution - the latest official version 4.4 [recommended]

Zabbix 2019/10/12 Chenxin refer to https://www.za...