手写 js数组reduce

2022-08-18 14:12:55 浏览数 (1)

代码语言:javascript复制
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

0 人点赞