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

Ubuntu 16.04 image complete installation tutorial under VMware

This article shares with you the installation tut...

A detailed summary of HTML tag nesting rules suitable for beginners

I have been relearning HTML recently, which can be...

Windows cannot start MySQL service and reports error 1067 solution

Suddenly when I logged into MySQL, it said that a...

How to clean up data in MySQL online database

Table of contents 01 Scenario Analysis 02 Operati...

How to load third-party component libraries on demand in Vue3

Preface Take Element Plus as an example to config...

Do you know the common MySQL design errors?

Thanks to the development of the Internet, we can...

CSS achieves the effect of two elements blending (sticky effect)

I remember that a few years ago, there was an int...

Analysis of the use and principle of Docker Swarm cluster management

Swarm Cluster Management Introduction Docker Swar...

Introduction to CSS style classification (basic knowledge)

Classification of CSS styles 1. Internal style --...

Linux operation and maintenance basic swap partition and lvm management tutorial

Table of contents 1. Swap partition SWAP 1.1 Crea...

JavaScript to add and delete messages on the message board

This article shares a small example of adding and...