Array.prototype.reduce()的简单应用

121 阅读1分钟

reduce实现map:

Array.prototype.mymap = function(fn){
    if(typeof fn !== 'function') return
    return this.reduce((pre, cur, index, arr) => {
        pre.push(fn(cur, index, arr))
        return pre
    }, [])
}

reduce后三个参数和Array.prototype.map的三个参数完全一致。 cur: 当前元素。 index: 元素索引。 arr: 原数组。 所以可以可以将累加器pre设置为空数组,将参数传入fn得到的结果push入累加器,最后得到的结果就与map一致了。

下面是一些其他用法:

// 数组累加
function arraySum(array) {
    if(!Array.isArray(array)) return
    return array.reduce((total, cur) => total + cur)
}

// 数组扁平化
function flat(array) {
    if(!Array.isArray(array)) return
    return array.reduce((pre, cur) => {
        console.log(cur)
        return pre.concat(cur)
    }, [])
}