面试时有时会遇到让实现一个reduce方法的问题,看了几篇关于手写reduce的文章后,发现充斥着一些错误写法,比如:
- 判断数组为空后直接返回。这种返回方式是错误的。官方的reduce函数在处理空数组时,会返回传入的初始值,如果没有传入初始值,此时会报错。
- 判断初始值是否存在时,使用三元运算符判断:
initialValue ? initialValue : this[0];这也是错误的,因为initialValue可能等于0,值为0不代表可以忽略。这样写会使传入的处理函数少调用一次,同样会影响结果。
研究了下总结了个正确版本:
Array.prototype.MyReduce = function(callbackFn, initial) {
if(typeof callbackFn !== 'function') {
throw new TypeError(callbackFn + 'is not a function');
}
if(this.length === 0 && initial === undefined) {
throw new TypeError('MyReduce of empty array with no initial value');
}
let startIndex, accumulator;
if(initial === undefined) {
startIndex = 1;
accumulator = this[0];
} else {
startIndex = 0;
accumulator = initial;
}
for(let i = startIndex;i < this.length;i ++) {
accumulator = callbackFn(accumulator, this[i], i, this);
}
return accumulator;
}
有错误的话欢迎大家指正。