基于自定义JavaScript Reduce实现ReduceRight(不反转数组)
基于自定义myReduce实现myReduceRight(不反转数组)
刚好可以利用你已经实现的myReduce来完成需求——我们不需要反转原数组,只需要生成一组反向索引,用myReduce遍历这些索引,每次取原数组对应位置的元素处理,就能模拟出从右到左的遍历逻辑。以下是具体实现:
Array.prototype.myReduceRight = function(cb, initialVal) { if (!cb) throw new Error("No CB defined"); const arrLength = this.length; // 处理空数组且无初始值的边界情况,和原生API行为对齐 if (arrLength === 0) { if (initialVal === undefined) throw new TypeError("Reduce of empty array with no initial value"); return initialVal; } let startAccumulator; let reversedIndices; if (initialVal === undefined) { // 无初始值时,初始累加器直接取原数组最后一个元素,索引从倒数第二位开始往前遍历 startAccumulator = this[arrLength - 1]; reversedIndices = Array.from({ length: arrLength - 1 }, (_, i) => arrLength - 2 - i); } else { // 有初始值时,用传入的初始值作为累加器起点,遍历所有反向索引 startAccumulator = initialVal; reversedIndices = Array.from({ length: arrLength }, (_, i) => arrLength - 1 - i); } // 复用自定义myReduce,遍历反向索引数组处理原数组元素 return reversedIndices.myReduce((acc, currentIndex) => { return cb.call(undefined, acc, this[currentIndex], currentIndex, this); }, startAccumulator); };
实现细节说明:
- 边界兼容:提前处理空数组无初始值的情况,抛出和原生
reduceRight一致的错误,保证API行为统一。 - 反向索引生成:通过
Array.from生成从数组末尾到开头的索引序列,完全不修改原数组结构。 - 参数对齐:回调函数的参数(累加器、当前元素、当前索引、原数组)和原生
reduceRight完全一致,使用起来没有差异。
测试验证:
// 无初始值求和 const arr1 = [1, 2, 3]; console.log(arr1.myReduceRight((acc, cur) => acc + cur)); // 输出6(3+2+1) // 带初始值求和 console.log(arr1.myReduceRight((acc, cur) => acc + cur, 10)); // 输出16(10+3+2+1) // 对象数组累加 const arr2 = [{x:1}, {x:2}, {x:3}]; console.log(arr2.myReduceRight((acc, cur) => acc + cur.x, 0)); // 输出6(0+3+2+1)
内容的提问来源于stack exchange,提问作者TechnoCorner
相关产品推荐
相关产品推荐

