1. forEach() is similar to map(). It also applies each element to the passed function in turn, but does not return a new array. 2. forEach() is often used to traverse an array, calling each element of the array and passing it to the callback function. Transfer functions do not need to return a value. Examples var arr = [7,4,6,51,1]; try{arr.forEach((item,index)=>{ if (item<5) { throw new Error("myerr") //Create a new error message for myerr } console.log(item)//Only print 7 to indicate that the loop has been exited})}catch(e){ console.log(e.message); if (e.message!=="myerr") { //If it is not the error we defined, just throw it away. throw e } } Knowledge point expansion: Handwritten forEach
If a thisArg parameter is provided to the let arr = [1, 2, 3, 4]; arr.forEach((...item) => console.log(item)); // [1, 0, Array(4)] Current value function Counter() { this.sum = 0; this.count = 0; } // Because the thisArg parameter (this) is passed to forEach(), each time it is called, it is passed to the callback function as its this value. Counter.prototype.add = function(array) { array.forEach(function(entry) { this.sum += entry; ++this.count; }, this); // ^---- Note }; const obj = new Counter(); obj.add([2, 5, 9]); obj.count; // 3 === (1 + 1 + 1) obj.sum; // 16 === (2 + 5 + 9)
Array.prototype.forEach = function(fn, thisArg) { var _this; if (typeof fn !== "function") { throw "the parameter must be a function"; } if (arguments.length > 1) { _this = thisArg; } if (!Array.isArray(arr)) { throw "forEach method can only be used on arrays"; } for (let index = 0; index < arr.length; index++) { fn.call(_this, arr[index], index, arr); } }; This is the end of this article about the detailed usage of js array forEach example. For more information about the usage of js array forEach method, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: CSS and HTML and front-end technology layer diagram
>>: Detailed explanation of the usage of MySQL data type DECIMAL
1. Pull the image docker pull registry.cn-hangzho...
Usage of having The having clause allows us to fi...
The first one is to use jQuery's ajax to send...
Use of AES encryption Data transmission encryptio...
I can log in to MYSQL normally under the command ...
In the past two days, I have been very troubled t...
1. Get is used to obtain data from the server, wh...
Preface: The "Getting Started with MySQL&quo...
For what I am going to write today, the program r...
Table of contents Preface Rolling principle accom...
This article uses an example to describe how MySQ...
Table of contents 1. Event Processing Model 1. Ev...
Table of contents Technology Stack Effect analyze...
Chinese Tutorial https://www.ncnynl.com/category/...
As usual, let’s first post the picture effect: Th...