reduce an array of methods

reduce method has two parameters, the first parameter is a function of the operation of array entries; second parameter is the initial value is passed, the most commonly used method is to reduce the superposition, the following examples can be seen, the function reduce initial values ​​0 constantly superimposed array items:

var items = [10, 120, 1000 ]; 

// sumSoFar first initial value is 1, item first initial value is the first element of the array, i.e., 10; 
var Total = items.reduce ( function the Add (sumSoFar, Item) { 
     // . 1 10 
    // . 11 120 
    // 131 is 1000 
    the console.log (sumSoFar, Item);
     return sumSoFar Item +;   // this value becomes the next sumSoFar 
},. 1 ); 

the console.log (Total ); // 1131    

reduce function that returns the result of the same type and an initial value passed, the previous example Type number initial value, the initial value may also be the object type:

var items = [10, 120, 1000 ]; 

// sumSoFar i.e., the first initial value {sum: 0}, item the first time the first element of the array 
var Total = items.reduce ( function (sumSoFar, Item) {
         // {SUM: 0 10} 
        // {SUM: 10} 120 
        // {SUM: 130.} 1000 
        the console.log (sumSoFar, Item); 
        sumSoFar.sum = + sumSoFar.sum Item; // for objects sumSoFar processed sum value, accumulated in the array each 
        return sumSoFar; // sumSoFar the target returns processed 
}, {sum: 0 }); 

the console.log (Total); // {sum: 1130.}
var ARR = [1,2,3,4,5,6,7,3,4,5,2,2,2 ]; 

// P first time as an initial value {}, k of the first array the first element, after each iteration of p after treatment (p [k] ++ || ( p [k] = 1)) of p 
var info = arr.reduce ( function (p, K) { 
        p [ K] ++ || (P [K] =. 1 );
         return P; 
}, {}); 

the console.log (info);   // {. 1:. 1, 2:. 4,. 3: 2,. 4: 2, 5: 2, 6: 1, 7: 1}

 

Guess you like

Origin www.cnblogs.com/xjy20170907/p/11119795.html