Iteration method
I personally think iteration methods are particularly important in Javascript. In many cases, there will be actual needs. Javascript provides 5 iteration methods for us to operate, and they are:
every() applies the given function to each item in the array. If each item returns true, it will return true.
filter() uses the given function for each item in the array, and combines the items that return true into a new array and returns
forEach() applies the given function to each item in the array, but does not have any 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() applies the given function to each item in the array. If an item in the array returns true, then it returns true.
Among the above 5 methods, they all accept two parameters: executing a function, that is, a function that needs to operate on each item. This function has three parameters: the value of the array item, the position of the item in the array, and the array object itself. Given a scope, given a scope, affects this object of the given function. like:
var values = [5,6,7,8,9,10,11,12,13]; function actionfunc(item, index, array){console.log(this)}; values.every(actionfunc,document); //The document object will be output 6 times to the consoleMerge method
In addition to iterative methods, JavaScript also provides two merge methods. Merge is archive merge. These methods, like names, will use the given function to iterate over each item in the array and then return a total value. The two merge methods are:
reduce() In the array, the term starts from the first to the last forward, the given function is applied to each item in the array, and then returns the sum of the results of running the given function on all items in the array.
reduceRight() applies the given function in the array from the last one to the first reverse, and then returns the sum of the results of running the given function on all items in the array.
The above two methods accept two parameters: Execution of a function, that is, a function that needs to operate on each item. This function has four parameters: the previous value, the current value, the index of the item, and the array object itself. The merged base value will be calculated based on this value. like:
var values = [5, 6, 7, 8, 9, 10, 11, 12, 13]; values.reduce(function(preitem,item,index,array){return preitem+item},2) //Return value 83The detailed explanation of the iteration and merge method in Javascript above is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.