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

Vue.js获取新冠疫情数据时如何计算当前值与前序值的差值

解决方案

直接在遍历原始接口返回数据时,通过遍历索引取前序记录做差即可,不需要额外多次遍历数组。
首先要保证数据按日期从早到晚升序排列,该接口默认返回顺序符合计算要求,增加一层排序兜底可以避免偶发的顺序错乱导致差值计算错误。

  • 最早一条记录没有更早的累计统计基线,当日新增值直接等于该条记录本身的累计值
  • 其余日期的新增值统一用当前项的累计数,减去上一条记录同维度的累计数
  • 增加异常兜底逻辑:如果计算出的差值为负(通常是统计口径调整、历史数据修正导致累计值回退),默认取0,避免出现不合理的负数新增数据

修正后完整代码

async fetchCovidDataByDay(){
    const res = await fetch(`https://api.covid19api.com/live/country/${this.name}/status/confirmed`);
    const data = await res.json();
    // 按日期升序排序兜底,保证计算顺序正确
    data.sort((a, b) => new Date(a.Date) - new Date(b.Date));
    
    this.arrConfirmed= [];
    this.arrDeaths = [];
    this.arrRecovered = [];
    this.arrActive = [];

    data.forEach((item, index) =>{
      const date = moment(item.Date).format('MMMM Do YYYY');
      const prevItem = index === 0 ? null : data[index - 1];
      // 计算各维度当日新增
      const newConfirmed = prevItem ? Math.max(0, item.Confirmed - prevItem.Confirmed) : item.Confirmed;
      const newDeaths = prevItem ? Math.max(0, item.Deaths - prevItem.Deaths) : item.Deaths;
      const newRecovered = prevItem ? Math.max(0, item.Recovered - prevItem.Recovered) : item.Recovered;
      const newActive = prevItem ? Math.max(0, item.Active - prevItem.Active) : item.Active;

      this.arrConfirmed.push({date, total: newConfirmed})
      this.arrDeaths.push({date, total: newDeaths})
      this.arrRecovered.push({date, total: newRecovered})
      this.arrActive.push({date, total: newActive})
    })
    return data;
  },

可选调整

如果业务需要同时保留累计值和当日新增值,可以在数组项中新增字段区分两类数据,示例:

this.arrConfirmed.push({
  date,
  total: item.Confirmed, // 原累计值
  newCount: newConfirmed // 当日新增值
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 03:48:23