Then yesterday's study, I found some simple and fun way of the array.
Merge method:
ECMAScript 5 adds two methods for merging arrays: reduce () and reduceright () . Both of these methods will overlap
All the items of an algebraic group, and then constructs a value that is ultimately returned. where the reduce () method starts with the first item in the array and iterates through the
To the end. The Reduceright () begins with the last item in the array and traverses forward to the first item.
Both methods receive two parameters: a function that is called on each item and (optionally) the initial value that is the base of the merge.
The functions passed to reduce () and reduceright () receive 4 parameters: The previous value, the current value, the index of the item, and the array object. This
Any value returned by a function will be automatically passed to the next item as the first argument. The first iteration occurs on the second item of the array, so the
One parameter is the first item of the array, and the second is the second item of the array.
Use the reduce () method to find the sum of all the values in the array:
var values = [1,2,3,4,5]; var sum = values.reduce (function(prev, cur, index, array) {return prev + // the
The first time the callback function is executed, prev is 1 and cur is 2. The second time, Prev is 3 (1 plus 2 result), Cur is 3 (array
The third item). This process continues until each item in the array is accessed again, and the result is returned.
Reduceright () acts similarly, except in the opposite direction.
Iteration method: None of the following methods will modify the contained values in the array
? Every (): Runs the given function for each item in the array, and returns True if the function returns true for each item.
? Filter (): Each item in an array runs the given function, and returns a list of items that are true of the function.
? ForEach (): Runs the given function for each item in the array. This method has no return value.
? Map (): Each item in the array runs the given function, returning an array that consists of the results of each function call.
? Some (): Runs the given function for each item in the array, and returns True if the function returns true for either item.
ECMAScript 5 defines 5 iterative methods for an array. Each method receives two parameters: a function to run on each item and a
(optional) The scope object that runs the function--the value that affects this. The functions passed in these methods receive three parameters: number
The value of the group item, the position of the item in the array, and the group object itself.
Chestnuts:
var numbers = [1,2,3,4,5,4,3,2,1]; var filterresult = Numbers.filter (function(item, index, array) {return (item > 2 //[3,4,5,4,3]
var numbers = [1,2,3,4,5,4,3,2,1]; var mapresult = Numbers.map (function(item, index, array) {return Item * 2 // [2,4,6,8,10,8,6,4,2]
Merging and iterative methods of arrays