You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现递增电表读数数组相邻元素差值计算

JavaScript计算电表读数相邻差值的实现

给定一组按周期(周/月/年)统计的递增电表读数数组,我们需要计算每两个相邻读数的差值,得到各周期的电量消耗数组。

输入输出示例

  • 输入电表读数数组:[18240,18290,18340,18400,18470,18510,18600]
  • 期望输出消耗数组:[50,50,60,70,40,90]

实现方法

方法1:for循环遍历

最直观的实现方式,从第二个元素开始逐个与前一个元素做差:

function calculateConsumption(readings) {
  const consumption = [];
  for (let i = 1; i < readings.length; i++) {
    consumption.push(readings[i] - readings[i - 1]);
  }
  return consumption;
}

// 测试代码
const meterReadings = [18240,18290,18340,18400,18470,18510,18600];
console.log(calculateConsumption(meterReadings)); // 输出 [50,50,60,70,40,90]

方法2:使用Array.map方法

通过slice(1)截取除第一个元素外的数组,再结合map计算差值:

const calculateConsumption = readings => 
  readings.slice(1).map((reading, index) => reading - readings[index]);

// 测试代码
const meterReadings = [18240,18290,18340,18400,18470,18510,18600];
console.log(calculateConsumption(meterReadings)); // 输出 [50,50,60,70,40,90]

方法3:使用Array.reduce方法

利用reduce的累加器特性,逐步构建消耗数组:

const calculateConsumption = readings => 
  readings.reduce((acc, curr, index) => {
    if (index > 0) {
      acc.push(curr - readings[index - 1]);
    }
    return acc;
  }, []);

// 测试代码
const meterReadings = [18240,18290,18340,18400,18470,18510,18600];
console.log(calculateConsumption(meterReadings)); // 输出 [50,50,60,70,40,90]

内容的提问来源于stack exchange,提问作者pb46

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 12:43:21