forEach() Method
in callback is a function executed for each element in the array, which can accept 1-3 parameters:
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 jsforEach 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) } }) SummarizeThis 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:
|
<<: Vue implements form data validation example code
1 Background JDK1.8-u181 and Tomcat8.5.53 were in...
React is a JAVASCRIPT library for building user i...
As we all know, there are two types of images in c...
I have encountered a problem. When testing the ed...
Table of contents 1. Problem Description 2. Probl...
question: Recently, garbled data appeared when de...
The reason for writing this article is that I wan...
AI image cutting needs to be coordinated with PS....
Table of contents 1. Prototype chain inheritance ...
1. Problem Sometimes when we log in to Mysql and ...
While the paperless world has not yet emerged, mo...
1. Cleaning before installation rpm -qa | grep jd...
Preface MySQL is a high-speed, high-performance, ...
Generally, on national days of mourning, days of ...
Table of contents 1. Create a Hadoop directory in...