JavaScript高次関数reduce方法の応用と原理分析


/**
 *  reduce()
 *          
 */
var arr = [1, 2, 3, 4, 5]

// es5  
var result = arr.reduce(function(prev, curr) {
    return prev + curr
})
console.log(result)

// es6  
var ret = arr.reduce((prev, curr) => prev + curr)
console.log(ret)
//   


// reduce          
//            prev                      5
//           prev      arr[0]  4

/**
 *    :     console.log(prev, curr);
 *    
 *      1   2       prev  curr
 *      3   3          prev+curr     prev
 *      6   4
 *      10  5
 *      15
 *                     
 */

//      

Array.prototype.myReduce = function(fn, initialValue) {
    if (this.length === 0) {
        if (initialValue === undefined) {
            console.error("reduce of empty array with no initialValue")
        } else {
            return initialValue
        }
    } else {
        var prev = initialValue !== undefined ? initialValue : this[0]
        var startIndex = initialValue !== undefined ? 0 : 1
        for (var i = startIndex; i < this.length; i++) {
            prev = fn(prev, this[i])
        }
        return prev
    }
}
var ret = arr.myReduce(function(prev, curr) {
    return prev + curr
}, 5)

console.log(ret)
//  user   age  
var user = [
    { name: '  ', age: 13 },
    { name: '  ', age: 15 },
    { name: '  ', age: 15 },
    { name: '  ', age: 17 }
]


var sumsAge = user.reduce(function(prev, curr) {
    //     prev   .age    prev    prev curr      .  age       
    return prev + curr.age
}, 0)
//   0   prev    
console.log(sumsAge);
//            user       
//  user         
console.log(user.reduce(function(prev, curr) {
    // console.log(prev, curr)
    prev.push({
        name: curr.name,
        age: curr.age
    })
    return prev
}, []))