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
This article shares with you the installation tut...
I have been relearning HTML recently, which can be...
Suddenly when I logged into MySQL, it said that a...
Because I wrote the word transition incorrectly i...
Table of contents 01 Scenario Analysis 02 Operati...
Preface Take Element Plus as an example to config...
Thanks to the development of the Internet, we can...
I remember that a few years ago, there was an int...
Swarm Cluster Management Introduction Docker Swar...
Classification of CSS styles 1. Internal style --...
The method of wrapping the content (title attribut...
Table of contents UI Design Echarts example effec...
Download from official website: https://www.mysql...
Table of contents 1. Swap partition SWAP 1.1 Crea...
This article shares a small example of adding and...