如何使用JavaScript开发天气预报表格?附代码片段
Improvements for Your Weather Forecast Table in JavaScript
Hey there! Let's break down your current code and walk through how to make this weather table functional, clean, and user-friendly.
First, here's your original code formatted for clarity:
for (var i = 0; i < data.list.length; i++) { table += "<tr>"; table += "<td>" + days[new Date(data.list[i].dt * 1000).getDay()] + "</td>"; table += "</tr>"; table += "<tr>"; table += "<td><img src='img/" + data.list[i].weather[0].description + ".svg'></td>"; table += "</tr>"; table += "<tr>"; table += "<td>" + data.list[i].weather[0].description + "</td>"; // Looks like your code cuts off here! }
Key Issues & Fixes
- Broken Table Structure: Right now, you're creating 3 separate
<tr>elements per weather entry. This will make your table layout messy—each row should represent a single day's forecast, with multiple<td>s for different data points (day, icon, description, temp, etc.). - Outdated Syntax: Using
varcan lead to scope issues; switch tolet/constinstead. Also, template literals (backticks`) make HTML string way easier to write and debug than concatenation. - Incomplete Data: Your current code only shows the day of the week, icon, and partial description. Let's add useful metrics like temperature, humidity, or wind speed to make the table more practical.
- Missing Error Handling: What if
data.listis empty, or a weather entry doesn't have the expected fields? Adding simple checks prevents broken UI from unexpected data gaps.
Improved Code Example
Here's a polished version that fixes these issues and adds more functionality:
// Assume `days` is your array of weekday names, e.g. ["Sun", "Mon", ..., "Sat"] const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; let table = "<table><thead><tr><th>Day</th><th>Icon</th><th>Condition</th><th>Temp (°C)</th><th>Humidity</th></tr></thead><tbody>"; // Guard clause to handle missing data if (!data?.list || data.list.length === 0) { table += "<tr><td colspan='5'>No forecast data available</td></tr>"; } else { for (const entry of data.list) { const date = new Date(entry.dt * 1000); const weekday = days[date.getDay()]; const fullDate = `${date.getMonth() + 1}/${date.getDate()}`; // MM/DD format const weather = entry.weather?.[0]; const temp = Math.round(entry.main.temp - 273.15); // Convert Kelvin to °C if (!weather) continue; // Skip entries with no weather data table += ` <tr> <td>${weekday}<br>${fullDate}</td> <td><img src='img/${weather.description.replace(/\s+/g, "-")}.svg' alt='${weather.description}' /></td> <td>${weather.description.charAt(0).toUpperCase() + weather.description.slice(1)}</td> <td>${temp}°C</td> <td>${entry.main.humidity}%</td> </tr> `; } } table += "</tbody></table>"; // Insert the table into your DOM element, e.g. document.getElementById("weather-table").innerHTML = table;
Extra Tips
- Icon Paths: We replaced spaces in the weather description with hyphens (
replace(/\s+/g, "-"))—this matches common file naming conventions (e.g., "clear sky" becomes "clear-sky.svg"). - Capitalization: We capitalize the first letter of the weather description for better readability.
- Temperature Conversion: Most weather APIs return temp in Kelvin, so we convert it to Celsius here (adjust to Fahrenheit if needed:
Math.round((entry.main.temp - 273.15) * 9/5 + 32)). - Semantic HTML: Added
<thead>to define table headers, making the table more accessible to screen readers.
内容的提问来源于stack exchange,提问作者James Miller
相关产品推荐
相关产品推荐

