JavaScript 使用 reduce 计算指定时间范围内的微信步数

本文将演示如何使用 JavaScript 的 reduce 方法,在一次循环中计算指定时间范围内的微信步数。这将优化使用 filter 和 reduce 两次循环的效率。

问题: 假设我们有一个数组 steps,存储了每天的微信步数,我们希望计算某个时间范围内所有步数的总和。

解决方案: 我们可以使用 reduce 方法来遍历每个步数,并判断当前日期是否在指定时间范围内。如果是,则将步数累加到总步数中。

代码示例:

const steps = [100, 200, 300, 400, 500, 600, 700];

const startDate = new Date('2022-01-01');
const endDate = new Date('2022-01-03');

const totalSteps = steps.reduce((acc, cur, index) => {
  const currentDate = new Date(startDate);
  currentDate.setDate(startDate.getDate() + index);
  if (currentDate >= startDate && currentDate <= endDate) {
    return acc + cur;
  }
  return acc;
}, 0);

console.log(totalSteps); // 1000

解释:

  • reduce 方法用于累积数组中的元素。
  • acc 参数代表累加器,初始值为 0。
  • cur 参数代表当前遍历的步数。
  • index 参数代表当前步数的索引。
  • 在 reduce 方法中,我们创建了一个 currentDate 对象,并将它的日期设置为 startDate 加上 index 天。
  • 我们判断 currentDate 是否在 startDate 和 endDate 之间。如果是,则将 cur 加到 acc 上,否则不做处理。
  • 最后,reduce 方法返回累加器 acc,也就是所有符合条件的步数之和。

结论: 通过使用 reduce 方法,我们可以在一次循环中计算指定时间范围内的微信步数,避免了使用 filter 和 reduce 两次循环的效率低下。

JavaScript 使用 reduce 计算指定时间范围内的微信步数

原文地址: https://www.cveoy.top/t/topic/ncrK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录