手写 js数组reduce

function reduce(list, fn, ...init) {
    let prev = init.length > 0 ? init[0] : list[0];
    for (let i = init.length > 0 ? 0 : 1; i < list.length; i++) {
        prev = fn(prev, list[i], i);
    }
    return prev;
}
console.log(
    reduce([1, 2, 3], (prev, cur, index) => {
        return prev + cur;
    })
);

MDN 文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

posted @ 2022-08-18 01:00  蓓蕾心晴  阅读(67)  评论(0编辑  收藏  举报