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

如何更新Map同键值?构建嵌套累计统计Map的技术咨询

问题:构建嵌套Map实现年度月度生鱼片累计量 & Map键值更新方法

需求说明

需要构建一个嵌套Map结构:

  • 外层Map以年份为键,对应值为内层Map
  • 内层Map以月份为键,对应值为累计食用的生鱼片数量
  • 累计规则:2010年January对应6737,February对应6737+7244;2011年January对应2010年全年累计总值加6737,以此类推逐年累计

同时需要了解:如何为Map中同一键设置新值

原代码

let sashimiPerMonth = [
  6737, 7244, 5776, 9826, 7057, 9247, 5842, 5484, 6543, 5153, 6832, 8274,
];
let months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
];

let years = [
  2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021,
];
let tempVal = 0
let dataMonth = [];
let dataYear = {};
const yearMap = new Map();
const monthMap = new Map();
for (let i = 0; i < years.length; i++) {
  for (let i = 0; i < months.length; i++) {
    let totalSashimi = sashimiPerMonth[i] + tempVal;
    dataMonth.push(totalSashimi);
    tempVal = tempVal + sashimiPerMonth[i];
    monthMap.set(months[i], dataMonth);
  }
  yearMap.set(years[i], monthMap.set(months[i], dataMonth));
}
console.log(yearMap);
console.log(dataYear);

原代码问题分析

  1. 内外层循环使用了同一个变量i,导致外层循环仅执行一次
  2. 所有年份共用同一个monthMap,数据会被后续年份覆盖
  3. dataMonth是全局数组,未按年份重置,导致数据混乱
  4. 累计逻辑未区分年度,无法实现逐年叠加的需求

正确实现代码

const sashimiPerMonth = [
  6737, 7244, 5776, 9826, 7057, 9247, 5842, 5484, 6543, 5153, 6832, 8274,
];
const months = [
  'January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December',
];
const years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021];

// 计算单年的月度累计值
const annualMonthlyCumulative = [];
let annualTotal = 0;
for (const num of sashimiPerMonth) {
  annualTotal += num;
  annualMonthlyCumulative.push(annualTotal);
}
const annualTotalSum = annualTotal; // 单年总累计量

// 构建嵌套Map
const yearMap = new Map();
let globalCumulative = 0; // 全局累计值,记录到上一年的总累计

for (const year of years) {
  const monthMap = new Map();
  // 为当前年份的每个月份计算累计值
  for (let i = 0; i < months.length; i++) {
    const cumulative = globalCumulative + annualMonthlyCumulative[i];
    monthMap.set(months[i], cumulative);
  }
  yearMap.set(year, monthMap);
  // 更新全局累计:加上当前年份的总累计
  globalCumulative += annualTotalSum;
}

// 测试输出示例
console.log(yearMap.get(2010).get('January')); // 6737
console.log(yearMap.get(2010).get('February')); // 13981
console.log(yearMap.get(2011).get('January')); // 2010全年累计 + 6737

Map同一键设置新值的方法

Map的set()方法本身就支持覆盖已有键的值:

  • 如果键不存在,map.set(key, value)会新增该键值对
  • 如果键已存在,map.set(key, newValue)会直接覆盖旧值

示例:

const testMap = new Map();
testMap.set('a', 1);
console.log(testMap.get('a')); // 1

// 同一键设置新值
testMap.set('a', 2);
console.log(testMap.get('a')); // 2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:11:12