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

如何将多数组对象转为每日数组并动态生成7天天气预报卡片

7天天气预报动态生成解决方案

第一步:整理每日预报数据

先把原始的四个数组按索引组合成结构化的每日预报数据,用map方法可以高效完成,确保每个索引对应的日期、天气代码、温区数据一一对应:

// 假设你的原始数据结构是这样
const weatherRawData = {
  time: ['2024-05-20', '2024-05-21', '2024-05-22', '2024-05-23', '2024-05-24', '2024-05-25', '2024-05-26'],
  weather_code: [0, 100, 200, 300, 0, 100, 200],
  temperature_2m_min: [12, 14, 11, 13, 15, 14, 12],
  temperature_2m_max: [25, 27, 23, 24, 26, 28, 24]
};

// 转换为结构化的每日预报数组
const dailyForecasts = weatherRawData.time.map((date, index) => ({
  date: date,
  weatherCode: weatherRawData.weather_code[index],
  tempMin: weatherRawData.temperature_2m_min[index],
  tempMax: weatherRawData.temperature_2m_max[index]
}));

第二步:动态生成预报卡片

提前在HTML中准备卡片容器,然后遍历整理后的每日数据,逐个创建DOM元素并插入容器,替代手动写7个卡片的重复工作:

HTML容器

<!-- 提前准备存放预报卡片的容器 -->
<div id="forecast-container" class="forecast-grid"></div>

JavaScript动态生成逻辑

// 获取容器元素
const forecastContainer = document.getElementById('forecast-container');

// 天气代码到图标的映射(根据你的实际图标方案调整,比如用SVG、字体图标类名)
const weatherIconMap = {
  0: '☀️',
  100: '⛅',
  200: '🌧️',
  300: '❄️',
  // 补充更多天气代码的映射
};

// 遍历生成每个卡片
dailyForecasts.forEach(day => {
  // 创建卡片主容器
  const card = document.createElement('div');
  card.classList.add('forecast-card');

  // 日期元素
  const dateEl = document.createElement('div');
  dateEl.className = 'card-date';
  dateEl.textContent = day.date;
  card.appendChild(dateEl);

  // 天气图标元素
  const iconEl = document.createElement('div');
  iconEl.className = 'card-icon';
  iconEl.textContent = weatherIconMap[day.weatherCode] || '❓';
  // 如果用图标库(比如Font Awesome),可以替换为:
  // iconEl.className = `card-icon fa ${weatherIconMap[day.weatherCode]}`;
  card.appendChild(iconEl);

  // 温度范围元素
  const tempEl = document.createElement('div');
  tempEl.className = 'card-temp';
  tempEl.textContent = `${day.tempMin}°C - ${day.tempMax}°C`;
  card.appendChild(tempEl);

  // 将卡片插入容器
  forecastContainer.appendChild(card);
});

配套CSS参考(可选)

提前写好卡片样式,让动态生成的卡片和手动创建的样式一致:

.forecast-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 1rem;
  padding: 1rem;
}

.forecast-card {
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 1rem;
  text-align: center;
}

.card-date {
  font-size: 0.9rem;
  color: #666;
}

.card-icon {
  font-size: 2rem;
  margin: 0.5rem 0;
}

.card-temp {
  font-weight: 500;
}

关键注意事项

  • 确保原始的四个数组长度完全一致(都是7),避免索引越界问题
  • 天气图标映射可以根据你使用的图标系统调整,比如用SVG图片的话,直接设置img标签的src属性即可
  • 如果需要处理日期格式化(比如显示“周一”“5/20”),可以用Date对象或者日期处理工具优化显示格式

内容的提问来源于stack exchange,提问作者stand-twilight-nag

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:35:29