我制作了一个应用程序,你可以在网站上看到雨的百分比。我用开胸疗法来获取数据。但是api响应输出了很多数组。怎么才能把它切成一个?(我要打印的数组的第一个零)我会发布回复的图片。

以下是代码:
const api_url = 'https://api.openweathermap.org/data/2.5/onecall?lat=52.1092717&lon=5.1809676&&exclude=current,minutely,timezone,alerts&appid=add524720c6b11d0649d761f76e953c8';
async function getRain() {
const response = await fetch(api_url);
const data = await response.json();
const {
hourly
} = data;
const popArr = hourly.map(element => element.pop);
hourly.forEach(element => {
console.log(element.pop);
});
// document.getElementById('pop').textContent = pop;
document.getElementById('pop').textContent = popArr;
}
getRain();<div id="maintext">
<p>De regen percentage is: <br><span id="pop"></span>%</p>
</div>
发布于 2022-04-27 18:25:16
你的数据每小时来一次。也许你现在想表现一下?
const api_url = 'https://api.openweathermap.org/data/2.5/onecall?lat=52.1092717&lon=5.1809676&&exclude=current,minutely,timezone,alerts&appid=add524720c6b11d0649d761f76e953c8';
async function getRain() {
const response = await fetch(api_url);
const data = await response.json();
const { hourly } = data;
const popList = {}
hourly.forEach(({dt,pop}) => popList[new Date(dt*1000).toLocaleString().split(",")[1].trim()] = pop);
const time = `${new Date().toLocaleString().match(/(\d{2}):/)[1]}:00:00`;
document.getElementById('pop').innerHTML = `${time}: ${popList[time]}%`; // percentage at nearest hour
}
getRain();<div id="maintext">
<p>De regen percentage is: <br><span id="pop"></span></p>
</div>
发布于 2022-04-27 19:09:59
您应该只从逐时数组中获得第一项:
const api_url = "https://api.openweathermap.org/data/2.5/onecall?lat=52.1092717&lon=5.1809676&&exclude=current,minutely,timezone,alerts&appid=add524720c6b11d0649d761f76e953c8";
async function getRain() {
const response = await fetch(api_url);
const data = await response.json();
const { hourly } = data; // get hourly data in array of objects form
// THE CRUCIAL CODE YOU FORGOT
// You must ONLY GET THE FIRST ITEM from the "hourly" array
const firstHourData = hourly[0]; // Get the first hour data object from "hourly" array
document.getElementById("pop").textContent = firstHourData.pop;
}
getRain();<div id="maintext">
<p>De regen percentage is: <br /><span id="pop"></span>%</p>
</div>
替代方式( JS编码器常用的方式)
const api_url = "https://api.openweathermap.org/data/2.5/onecall?lat=52.1092717&lon=5.1809676&&exclude=current,minutely,timezone,alerts&appid=add524720c6b11d0649d761f76e953c8";
async function getRainSimplified() {
await fetch(api_url)
.then((response) => {
return response.json();
})
.then(({ hourly }) => {
document.getElementById("pop").textContent = hourly[0].pop;
});
}
getRainSimplified();<div id="maintext">
<p>De regen percentage is: <br /><span id="pop"></span>%</p>
</div>
https://stackoverflow.com/questions/72033509
复制相似问题