【循环系列】reduceRight循环

274 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前言

发现JS中的循环有好多,如果让一下说出来,感觉有些会想不起来,本次花时间来梳理一下JS中循环语句。

本系列相关文章:

  1. 【循环系列】for循环和while循环
  2. 【循环系列】for in和forEach循环
  3. 【循环系列】之map循环
  4. 【循环系列】filter和some循环
  5. 【循环系列】every循环
  6. 【循环系列】reduce循环 本文是本系列第7篇,关于reduceRight循环

reduceRight

reduceRightreduce极其相似,只不过reduce中的回调累积total的时候,是从左往右,而reduceRight是从右往左。例如以下代码:

let arr = [1, 2, 3, 4, 5];
let res = arr.reduceRight((total, cur, index, arr) => {
    console.log(total, cur, index, arr);//每一次的tatal就是上一次的循环执行的返回结果
    return total + cur;
});
console.log(res)

结果

下面来手动实现一个:_reduceRight

Array.prototype._reduceRight = function (fn, thisTo) {
  let total = this[this.length - 1];
  for (let i = this.length - 1 - 1; i >= 0; i--) {
    total = fn.call(thisTo, total, this[i], i, this)
  }
  return total;
}
let arr = [1, 2, 3, 4, 5];
let res = arr._reduceRight((total, cur, index, arr) => {
  console.log(total, cur, index, arr); //每一次的tatal就是上一次的循环执行的返回结果
  return total + cur;
});
console.log(res)

如上结果,可以看到成功实现了reduceRight的功能

结束

以上就是reduceRight循环的相关内容