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