我正在努力让它发挥作用:
(删除应用程序ID)
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;
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);
// Update the weather values on your web page
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));
const "rain" > data.rain['1h'] 并不总是可用,如果它可用,上面的代码就可以工作,但如果它不可用,则会导致:“无法读取未定义的属性(读取 '1h')”
我尝试用“ || '0' 修复它;但这似乎不起作用......
基本上如果没有下雨,应该显示0。
谢谢您的帮助!
使用符号“?”为了防止此类错误:
const rain = data?.rain?.['1h'] || '0';