Detailed Explanation of js Array forEach Instance Usage

  • 2021-11-29 22:59:39
  • OfStack

1. forEach () is similar to map () in that it also applies each element to the incoming function in turn, but does not return a new array.

2. forEach () is often used to traverse arrays, calling every element of the array and passing it to the callback function. The transfer function does not need to return a value.

Instances


var arr=[7,4,6,51,1];
try{arr.forEach((item,index)=>{
      if (item<5) {
       throw new Error("myerr")// Create 1 A new one error message For myerr
      }
      console.log(item)// Print only 7  Explain that the loop jumped out 
     })}catch(e){
            console.log(e.message);
      if (e.message!=="myerr") {// If only it wasn't the mistake we defined, we would throw it away 
       throw e
      }
     }

Extension of knowledge points:

Handwritten forEach

forEach() Method executes the supplied function once on each element of the array

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

callback

currentValue
The current element being processed in the array. index optional
The index of the current element being processed in the array. array optional
The array that the forEach () method is working on. thisArg optional
Optional parameter. When the callback function callback is executed, it is used as the value of this. No return value

If 1 thisArg parameter is supplied to forEach Function, the argument will be used as the this Value. Otherwise this The value is undefined. Callback function this The binding of is based on the common when the function is called this Bind rules to determine.


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  thisArg  Parameters ( this ) 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 Callback parameters are: every 1 item, index, original array

Array.prototype.forEach = function(fn, thisArg) {
 var _this;
 if (typeof fn !== "function") {
  throw " Argument must be a function ";
 }
 if (arguments.length > 1) {
  _this = thisArg;
 }
 if (!Array.isArray(arr)) {
  throw " Can only be used for arrays forEach Method ";
 }

 for (let index = 0; index < arr.length; index++) {
  fn.call(_this, arr[index], index, arr);
 }
};


Related articles: