我写了减少JavaScript的本机实现。但是我正在寻找是否可以使用此reduce来实现ReduceRight。
Array.prototype.myReduce = function(cb, initialVal) {
if (!cb)
throw new Error("No CB defined");
let [accumulator, ...arr] = initialVal === undefined ? [...this] : [initialVal, ...this];
for (var i = 0; i < this.length; i++) {
accumulator = cb.call(undefined, accumulator, arr[i], i, arr);
}
return accumulator;
}
我从this article读到
现在您可能会注意到一些事情。不只是地图的一种特殊情况
减少?是!实际上,我们可以根据reduce的表亲来实现map
reduceRight。 reduceRight就像reduce一样,只不过它减少了
反向列出项目。因此,它将首先遇到Nil,
然后是倒数第二个项目,继续前进直到到达第一个项目为止
列表中的项目。 reduceRight可以实现如下:
我无法理解如何实现reduceRight(无需反转数组)
这是我的实现:
Array.prototype.myReduceRight2 = function(cb, initialVal) {
if (!cb)
throw new Error("No CB defined");
const arr = [...this].reverse(); //DONOT REVERSE! Looking for alternate solution(s)
const res = arr.myReduce((acc, val) => {
return acc.concat(val);
}, initialVal); // pass initialVal
return res;
}
最佳答案
以下是我在个人库中使用的reduceRight
的实现。
码:
Array.prototype.myReduceRight = function(callback, initialValue) {
var
/* Cache the length of the context. */
length = this.length >>> 0,
/* Create a counter defaulting at the index of the last element in the context. */
counter = length - 1;
/* Check whether a second argument has been given or not. */
if (arguments.length < 2) {
/* Repeat until the counter is less than or equal to the length of the
context or when the counter exists as an index in the context. */
while (counter >= 0 && !(counter in this)) {
/* Decrement the counter. */
counter--;
}
/* Set the inital value. */
initialValue = this[counter--];
}
/* Repeat until the counter is less than 0. */
while (counter >= 0) {
/* Check whether the counter exists as an index in the context. */
if (counter in this) {
/* Set the initial value to be the return value of the given callback. */
initialValue = callback.call(this, initialValue, this[counter], counter, this);
}
/* Decrement the counter. */
counter--;
}
/* Return the calculated value. */
return initialValue;
}
const array = [1, 2, 3, 4];
console.log(array.myReduceRight((acc, cur) => acc + cur));
关于javascript - ReduceRight而不反转数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49582290/