Detailed Iteration and Merge Method in Javascript

  • 2021-06-28 10:40:35
  • OfStack

Iteration method

Iteration methods in Javascript are of particular importance to us personally, and there are real needs in many cases. javascript provides five iteration methods for us to operate on, which are:

every() uses the given function for each item in the array, and if each item returns true, then true is returned

filter() uses the given function on each item in the array to make a new array of items returned to true and return them

forEach() uses the given function for each item in the array, but has no return value

map() applies the given function to each item in the array and returns the result of each function call to form a new array

same() uses the given function for each item in the array, and returns true if one item in the array returns true

Of the five methods above, they all accept two parameters: the execution function, which is the function that needs to operate on each item. The function has three parameters: the value of the array item, the position of the item in the array, and the array object itself.Given scope, given a scope, affects the this object for a given function.For example:


var values = [5,6,7,8,9,10,11,12,13];
 
function actionfunc(item, index, array){console.log(this)};
 
values.every(actionfunc,document); // This will output to the console 6 second document object 

Merge method

In addition to the iterative methods, javascript also provides two merging methods, which, like the name 1, iterate through each item in the array using a given function and return a total value.The two merging methods are:

reduce() applies the given function to each item in the array from the first to the last forward logarithm, and then returns the sum of the results of running the given function on all items of the array.

reduceRight() uses the given function backwards from the last item in the array to the first, and then returns a sum of the results of running the given function on all items in the array.

The two methods above take two parameters: the execution function, which is the function that needs to operate on each item. The function has four parameters: the first value, the current value, the index of the item, and the array object itself.The basis value of the merge, which is the basis for the merge calculation.For example:


var values = [5, 6, 7, 8, 9, 10, 11, 12, 13];
 
values.reduce(function(preitem,item,index,array){return preitem+item},2) // Return Value 83

Related articles: