Openweathermap API获取rain['1h']属性时未定义错误的解决求助
解决OpenWeatherMap API降雨数据不存在时的报错问题
问题出在当无降雨时,API返回结果里没有rain字段,此时直接访问data.rain['1h']等同于读取undefined['1h'],会直接抛出报错——你的|| '0'逻辑根本没机会执行,因为报错发生在逻辑或运算之前。
以下是几种可行的修复方案:
方案1:使用可选链+空值合并操作符(推荐)
这是ES2020+的语法,简洁且安全:
const rain = data.rain?.['1h'] ?? 0;
?.会先检查data.rain是否存在(不为undefined/null),不存在则直接返回undefined??会在左侧值为undefined或null时,返回右侧的0,避免把0、空字符串等合法值覆盖
方案2:短路求值兼容旧环境
如果需要兼容不支持ES2020的环境,可以用多层短路判断:
const rain = (data.rain && data.rain['1h']) || 0;
- 先判断
data.rain是否存在,存在才继续访问['1h'] - 如果
data.rain不存在或data.rain['1h']为假值(比如0),则返回0
方案3:显式条件判断
更直观的写法,适合需要额外逻辑的场景:
let rain = 0; if (data.rain && '1h' in data.rain) { rain = data.rain['1h']; }
修改后的完整代码示例
fetch('https://api.openweathermap.org/data/2.5/weather?lat=39.561937&lon=2.936562&appid=XXX&units=metric&lang=de') .then(data => data.json()) .then(data => { const description1 = data.weather[0].description; const temperature = data.main.temp; const feels = data.main.feels_like; const wind1 = data.wind.speed; // 替换为方案1的写法 const rain = data.rain?.['1h'] ?? 0; const weatherIcon = document.querySelector('.icon img'); const iconURL = `https://openweathermap.org/img/wn/${data.weather[0].icon}.png`; weatherIcon.setAttribute('src', iconURL); // 更新网页上的天气数值 document.querySelector('#description1').innerText = description1; document.querySelector('#temperature').innerText = Math.round(temperature); document.querySelector('#feels').innerText = Math.round(feels); document.querySelector('#wind1').innerText = Math.round(wind1 * 3.6); document.querySelector('#rain').innerText = rain; }) .catch(error => console.log(error));
内容的提问来源于stack exchange,提问作者Kees
相关产品推荐
相关产品推荐

