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

如何使用for循环加载2015-2018年各年度water_supply数组数据

解决思路

首先梳理你原有手动代码的索引规律:

  • 共4个年份(2015-2018),对应res.data.table的行偏移量分别为1、2、3、4
  • 共8个城市,每个城市在同一年份的行间隔为4,即第i个城市的行号为 年份偏移量 + 4*i

最优实现方案(推荐)

直接用二维数组存储所有年份数据,避免定义多个零散变量,后续维护更方便:

const sortedData = ["BUF", "CCT", "EKH", "ETK","JHB", "MAN", "NMB", "TSH"]
// 二维数组:waterSupply[0]对应2015年数据,waterSupply[1]对应2016年,以此类推
const waterSupply = Array.from({length:4}, ()=>[])

// 外层循环遍历4个年份
for(let yearIdx = 0; yearIdx < 4; yearIdx++){
  const rowOffset = yearIdx + 1 // 年份行偏移:2015年为1、2016年为2...
  // 内层循环遍历8个城市
  for(let cityIdx = 0; cityIdx < sortedData.length; cityIdx++){
    const rowIndex = rowOffset + 4 * cityIdx
    waterSupply[yearIdx][cityIdx] = res.data.table[rowIndex].slice(2,3)[0]
  }
}

// 验证输出
console.log('2015年数据:', waterSupply[0])
console.log('2016年数据:', waterSupply[1])
console.log('2017年数据:', waterSupply[2])
console.log('2018年数据:', waterSupply[3])

兼容原有变量名方案

如果确实需要保留water_supply1到water_supply4的变量定义,可以用动态变量名实现:

const sortedData = ["BUF", "CCT", "EKH", "ETK","JHB", "MAN", "NMB", "TSH"]
for(let yearIdx = 0; yearIdx <4; yearIdx++){
  const rowOffset = yearIdx + 1
  const currentArray = window[`water_supply${yearIdx+1}`] = []
  for(let cityIdx=0; cityIdx < sortedData.length; cityIdx++){
    const rowIndex = rowOffset + 4 * cityIdx
    currentArray[cityIdx] = res.data.table[rowIndex].slice(2,3)[0]
  }
}

原代码问题说明

你之前的写法只循环了城市维度,没有加外层的年份循环,所以只能生成单年的数组数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:48:01