Detailed usage of js array forEach instance

Detailed usage of js array forEach instance

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

forEach() method executes a provided function once for each element of an array

arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);

  • callback

    • currentValue
      The current element being processed in the array.
    • index Optional The index within the array of the current element being processed.
    • array optional
      The array that the forEach() method is operating on.
    • thisArg OptionalOptional parameter. Used as the value of this when the callback function is executed.
  • No return value

If a thisArg parameter is provided to the forEach function, the parameter will be used as this value in the callback function. Otherwise the value of this is undefined . The binding of this in the callback function is determined according to the general this binding rules when the function is called.

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)

  • Every array has this method
  • The callback parameters are: each item, index, original array
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:
  • Object.entries usage you don't know in JavaScript
  • js array fill() filling method
  • Detailed discussion of several methods for deduplicating JavaScript arrays
  • Summary of JS tips for creating or filling arrays of arbitrary length
  • Detailed explanation of the deep and shallow cloning principles of JavaScript arrays and non-array objects
  • Detailed explanation of JavaScript array deduplication
  • js array entries() Get iteration method

<<:  CSS and HTML and front-end technology layer diagram

>>:  Detailed explanation of the usage of MySQL data type DECIMAL

Recommend

Detailed explanation of the process of building an MQTT server using Docker

1. Pull the image docker pull registry.cn-hangzho...

mysql having usage analysis

Usage of having The having clause allows us to fi...

Detailed explanation of the use cases of Vue listeners

The first one is to use jQuery's ajax to send...

Detailed steps for using AES.js in Vue

Use of AES encryption Data transmission encryptio...

Solution to IDEA not being able to connect to MySQL port number occupation

I can log in to MYSQL normally under the command ...

GET POST Differences

1. Get is used to obtain data from the server, wh...

Detailed explanation of long transaction examples in MySQL

Preface: The "Getting Started with MySQL&quo...

Detailed explanation of the correct use of the if function in MySQL

For what I am going to write today, the program r...

Vue sample code for easily implementing virtual scrolling

Table of contents Preface Rolling principle accom...

Detailed explanation of Javascript event capture and bubbling methods

Table of contents 1. Event Processing Model 1. Ev...

Basic tutorial on controlling Turtlebot3 mobile robot with ROS

Chinese Tutorial https://www.ncnynl.com/category/...

Sample code for implementing image drawer effect with CSS3

As usual, let’s first post the picture effect: Th...