js数组原型中有个reduce方法,是对数组一种隐式迭代的方法,一次面试竟被要求手写出来,结果败兴而归,在编辑器上尝试作出,看着没什么bug。
Array.prototype.reduce2 = function (fn, init) {
const {length} = this;
let hasInit = typeof init !== 'undefined', //判断是否有初始值
result = length === 1 ? this[0] : fn(hasInit ? init : this[0], hasInit ? this[0] : this[1]), //目标数组只有一个值的话则直接返回这个值
i = hasInit ? 1 : 2;
if (i === 2 && length === 2 || length === 1) {
return result;
}
//参数函数循环执行目标数组中相邻的两个值
while (i < length) {
result = fn(result, this[i++])
}
return result;
};